Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move decimal?

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?

like image 644
Flafla2 Avatar asked Apr 25 '11 03:04

Flafla2


People also ask

When you move a decimal to the left?

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.


4 Answers

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.

like image 143
alex Avatar answered Oct 14 '22 23:10

alex


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.

like image 32
Rudie Avatar answered Oct 15 '22 01:10

Rudie


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
like image 37
Peter Olson Avatar answered Oct 15 '22 01:10

Peter Olson


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

like image 32
Delta Avatar answered Oct 15 '22 01:10

Delta