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?
value of the exponent. - If you moved the decimal point to the left, make the exponent positive. - If you moved the decimal point to the right, make the exponent negative.
var a = 5007;
// Where `1` below is the amount you want to move it.
a /= Math.pow(10, 1);
document.body.innerHTML = a; // 500.7
jsFiddle.
var n = 1234;
var l = n.toString().length-3;
var v = n/Math.pow(10, l); // new value
The 3
is because you want the first 3 digits as wholes, so the base changes depending on the size of n
.
function moveDecimal(n) {
var l = n.toString().length-3;
var v = n/Math.pow(10, l);
return v;
}
Try it for 1234, 12345 and 123456.
123456 is 123.456 multiplied by 1000. That means you could move the decimal place over with divisions:
var num1 = 1234 / 10; //sets num1 to 123.4
var num2 = 12345 / 100; //sets num2 to 123.45
var num3 = 123456 / 1000; //sets num3 to 123.456
Alternatively, if you want to set the number of decimal places in a more general form, you can use the Math.pow function:
var num3 = 123456 / Math.pow(10, 3); //sets num3 to 123.456
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With