Javascript 使用javascript将小数位添加到数字中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11524619/
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
Adding Decimal place into number with javascript
提问by Owen
I've got this number as a integer 439980
我有这个数字作为整数 439980
and I'd like to place a decimal place in 2 places from the right. to make it 4399.80
我想在右边的 2 位放置一个小数位。使其成为 4399.80
the number of characters can change any time, so i always need it to be 2 decimal places from the right.
字符数可以随时更改,所以我总是需要它是右边两位小数。
how would I go about this?
我该怎么办?
thanks
谢谢
回答by nnnnnn
function insertDecimal(num) {
return (num / 100).toFixed(2);
}
回答by jacobedawson
Just adding that toFixed() will return a string value, so if you need an integer it will require 1 more filter. You can actually just wrap the return value from nnnnnn's function with Number() to get an integer back:
只需添加 toFixed() 将返回一个字符串值,因此如果您需要一个整数,它将需要 1 个以上的过滤器。实际上,您可以使用 Number() 包装来自 nnnnnn 函数的返回值以获取整数:
function insertDecimal(num) {
return Number((num / 100).toFixed(2));
}
insertDecimal(99552) //995.52
insertDecimal("501") //5.01
The only issue here is that JS will remove trailing '0's, so 439980 will return 4399.8, rather than 4399.80 as you might hope:
这里唯一的问题是 JS 将删除尾随的 '0',因此 439980 将返回 4399.8,而不是您可能希望的 4399.80:
insertDecimal(500); //5
If you're just printing the results then nnnnnn's original version works perfectly!
如果您只是打印结果,那么 nnnnnn 的原始版本可以完美运行!
notes
笔记
JavaScript's Number function can result in some very unexpected return values for certain inputs. You can forgo the call to Number and coerce the string value to an integer by using unary operators
JavaScript 的 Number 函数可能会导致某些输入的一些非常意外的返回值。您可以放弃对 Number 的调用,并使用一元运算符将字符串值强制为整数
return +(num / 100).toFixed(2);
or multiplying by 1 e.g.
或乘以 1 例如
return (num / 100).toFixed(2) * 1;
TIL: JavaScript's core math system is kind of weird
TIL:JavaScript 的核心数学系统有点奇怪