Adding Decimal place into number with javascript

I've got this number as a integer 439980

and I'd like to place a decimal place in 2 places from the right. to make it 4399.80

the number of characters can change any time, so i always need it to be 2 decimal places from the right.

how would I go about this?



function insertDecimal(num) {
   return (num / 100).toFixed(2);

Just adding that toFixed() will return a string value, so if you need an integer it will require 1 more filter. You can actually just wrap the return value from nnnnnn's function with Number() to get an integer back:

function insertDecimal(num) {
   return Number((num / 100).toFixed(2));

insertDecimal(99552) //995.52
insertDecimal("501") //5.01

The only issue here is that JS will remove trailing '0's, so 439980 will return 4399.8, rather than 4399.80 as you might hope:

insertDecimal(500); //5

If you're just printing the results then nnnnnn's original version works perfectly!


JavaScript's Number function can result in some very unexpected return values for certain inputs. You can forgo the call to Number and coerce the string value to an integer by using unary operators

return +(num / 100).toFixed(2);

or multiplying by 1 e.g.

return (num / 100).toFixed(2) * 1;

TIL: JavaScript's core math system is kind of weird

Need Your Help

How can I change the CheckChanged when clicking the same object in VB 2010? winforms visual-studio-2010 checkbox

I want to know if it is possible in VB 2010 to changed the CheckChanged of a CheckBox when clicking the same object. For Example: