javascript 如何移动小数点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5774836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move decimal?
提问by Flafla2
In JavaScript, I want to define where the decimal place goes. I can only really show it in example.
在 JavaScript 中,我想定义小数点的位置。我只能在示例中真正展示它。
Lets say the input value is 1234
.
I want the output to be 123.4
.
假设输入值为1234
。
我希望输出为123.4
.
Or, if the input is 12345
, I want the output to be 123.45
.
或者,如果输入是12345
,我希望输出是123.45
。
Or, if the input is 123456
, I want the output to be 123.456
. You get the picture.
或者,如果输入是123456
,我希望输出是123.456
。你得到了图片。
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?
那么,这怎么可能呢?
回答by alex
回答by Peter Olson
123456 is 123.456 multiplied by 1000. That means you could move the decimal place over with divisions:
123456 是 123.456 乘以 1000。这意味着你可以用除法移动小数位:
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:
或者,如果要以更一般的形式设置小数位数,可以使用 Math.pow 函数:
var num3 = 123456 / Math.pow(10, 3); //sets num3 to 123.456
回答by Rudie
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
.
这3
是因为您希望将前 3 位数字作为整数,因此基数会根据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.
试试 1234、12345 和 123456。
回答by Delta
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.
基本数学,只需将数字除以 10 即可向左侧移动 1 个小数。乘以 10 则相反。
"Lets say the input value is 1234. I want the output to be 123.4"
“假设输入值为 1234。我希望输出为 123.4”
1234 / 10 = 123.4
1234 / 10 = 123.4
"Or, if the input is 12345, I want the output to be 123.45"
“或者,如果输入是 12345,我希望输出是 123.45”
12345 / 100 = 123.45
12345 / 100 = 123.45
回答by Blindy
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:
算出你想把小数点向左移动多少位,然后将你的数字除以 10 的幂:
123.456=123456/(10^3)
Where ^
is raise to the power.
哪里^
提升到权力。