How to move decimal?

2019-07-21 02:13发布

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?

5条回答
你好瞎i
2楼-- · 2019-07-21 02:19
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.

查看更多
smile是对你的礼貌
3楼-- · 2019-07-21 02:22
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.

查看更多
何必那么认真
4楼-- · 2019-07-21 02:22

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.

查看更多
Rolldiameter
5楼-- · 2019-07-21 02:23

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
查看更多
爷的心禁止访问
6楼-- · 2019-07-21 02:32

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

查看更多
登录 后发表回答