In JavaScript, I want to define where the decimal place goes. I can only really show it in example.
Lets say the input value is 1234
.
I want the output to be 123.4
.
Or, if the input is 12345
, I want the output to be 123.45
.
Or, if the input is 123456
, I want the output to be 123.456
. You get the picture.
To clarify, I just want three digits on the left side of the decimal. The total number of digits is unknown.
So, how could this be done?
jsFiddle.
The
3
is because you want the first 3 digits as wholes, so the base changes depending on the size ofn
.Try it for 1234, 12345 and 123456.
Figure out how many places you want to move the decimal point to the left and divide your number by 10 to the power of that number:
Where
^
is raise to the power.123456 is 123.456 multiplied by 1000. That means you could move the decimal place over with divisions:
Alternatively, if you want to set the number of decimal places in a more general form, you can use the Math.pow function:
Basic maths, just divide the number by 10 to move 1 decimal case towards the left side. And multiply by 10 to do the opposite.
"Lets say the input value is 1234. I want the output to be 123.4"
1234 / 10 = 123.4
"Or, if the input is 12345, I want the output to be 123.45"
12345 / 100 = 123.45