7

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?

alex
  • 479,566
  • 201
  • 878
  • 984
Flafla2
  • 691
  • 2
  • 11
  • 21
  • 1
    so basically you want the decimal point after the third digit? and do you need this as a string or are you using this for a mathematical operation? – corroded Apr 25 '11 at 03:15

5 Answers5

13
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.

alex
  • 479,566
  • 201
  • 878
  • 984
8

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
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
8
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.

Rudie
  • 52,220
  • 42
  • 131
  • 173
1

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

Delta
  • 4,308
  • 2
  • 29
  • 37
  • 1
    To clarify, i just want three digits on the left side of the decimal. The total number of digits is unknown. – Flafla2 Apr 25 '11 at 03:25
0

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:

123.456=123456/(10^3)

Where ^ is raise to the power.

Blindy
  • 65,249
  • 10
  • 91
  • 131