Javascript 限制javascript中小数点后显示的数字数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4256030/
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
Limit the amount of number shown after a decimal place in javascript
提问by dotty
Hay, i have some floats like these
嘿,我有一些这样的花车
4.3455
2.768
3.67
and i want to display them like this
我想像这样显示它们
4.34
2.76
3.67
I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.
我不想向上或向下舍入数字,只需将小数位后显示的数字数量限制为 2。
回答by T.J. Crowder
回答by C. J.
As T.J answered, the toFixed
method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.
正如 TJ 回答的那样,该toFixed
方法将在必要时进行适当的舍入。它还会添加尾随零,这并不总是理想的。
(4.55555).toFixed(2);
//-> "4.56"
(4).toFixed(2);
//-> "4.00"
If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.
如果将返回值转换为数字,则将删除那些尾随零。这是一种比自己进行四舍五入或截断数学运算更简单的方法。
+parseFloat((4.55555).toFixed(2));
//-> 4.56
+parseFloat((4).toFixed(2));
//-> 4
回答by Andy E
If you don't want rounding to 2 decimal places, use toFixed()
to round to ndecimal places and chop all those off but 2:
如果您不想四舍五入到 2 个小数位,请使用toFixed()
四舍五入到n个小数位并将所有这些都去掉,但 2 个:
var num = 4.3455.toFixed(20);
alert(num.slice(0, -18));
//-> 4.34
Note that this does have the slight downside of rounding when the number of decimal places passed to toFixed()
is less than the number of decimal places of the actual number passed in and those decimal places are large numbers. For instance (4.99999999999).toFixed(10)
will give you 5.0000000000
. However, this isn't a problem if you can ensure the number of decimal places will be lower than that passed to toFixed()
. It does, however, make @TJ's solution a bit more robust.
请注意,当传递给的小数位数toFixed()
小于传递的实际数字的小数位数并且这些小数位是大数时,这确实有舍入的轻微缺点。例如(4.99999999999).toFixed(10)
会给你5.0000000000
。但是,如果您可以确保小数位数低于传递给toFixed()
. 但是,它确实使@TJ 的解决方案更加强大。
回答by SC1000
Warning!The currently accepted solution fails in some cases, e.g. with 4.27 it wrongly returns 4.26.
警告!当前接受的解决方案在某些情况下会失败,例如 4.27 它错误地返回 4.26。
Here is a general solutionthat works always.
这是一个始终有效的通用解决方案。
(Maybe I should put this as a comment, but at the time of this writing, I don't have the required reputation)
(也许我应该把它作为评论,但在撰写本文时,我没有所需的声誉)
回答by NVRM
Good news everyone! Since a while there is an alternative: toLocaleString()
大家好消息!一段时间以来,有一个替代方案:toLocaleString()
While it isn't exactly made for rounding, there is some usefuls options arguments.
虽然它不是完全为四舍五入而制作的,但有一些有用的选项参数。
minimumIntegerDigits
最小整数位数
The minimum number of integer digits to use. Possible values are from 1 > to 21; the default is 1.
要使用的最小整数位数。可能的值是从 1 > 到 21;默认值为 1。
minimumFractionDigits
最小分数
The minimum number of fraction digits to use.
Possible values are from 0 > to 20; the default for plain number and percent formatting is 0; t
The default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).
要使用的最小小数位数。
可能的值是从 0 > 到 20;普通数字和百分比格式的默认值为 0;吨
货币格式的默认值是 ISO 4217 货币代码列表提供的次要单位位数(如果列表不提供该信息,则为 2)。
maximumFractionDigits
最大分数
The maximum number of fraction digits to use.
Possible values are from 0 > to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3
The default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.
要使用的最大小数位数。
可能的值是从 0 > 到 20;纯数字格式的默认值是 minimumFractionDigits 和 3 中的较大者
货币格式的默认值是 minimumFractionDigits 和 ISO 4217 货币代码列表提供的次要单位位数中的较大者(如果列表不提供该信息,则为 2);百分比格式的默认值是 minimumFractionDigits 和 0 中的较大者。
minimumSignificantDigits
最小有效数字
The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
要使用的最小有效数字位数。可能的值是从 1 到 21;默认值为 1。
maximumSignificantDigits
最大有效数字
The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.
要使用的最大有效数字位数。可能的值是从 1 到 21;默认值为 21。
Example usage:
用法示例:
var bigNum = 8884858284485 * 4542825114616565
var smallNum = 88885 / 4545114616565
console.log(bigNum) // Output scientific
console.log(smallNum) // Output scientific
// String
console.log(
bigNum.toLocaleString('fullwide', {useGrouping:false})
)
// Return a string, rounded at 12 decimals
console.log(
smallNum.toLocaleString('fullwide', {maximumFractionDigits:12})
)
// Return a string, rounded at 8 decimals
console.log(
smallNum.toLocaleString('fullwide', {minimumFractionDigits:8, maximumFractionDigits:8})
)
// Return an Integer, rounded as need, js will convert it back to scientific!
console.log(
+smallNum.toLocaleString('fullwide', {maximumFractionDigits:12})
)
// Return same Integer, don't use parseInt for precision!
console.log(
parseInt(smallNum.toLocaleString('fullwide', {maximumFractionDigits:12}))
)
Butthis does not match the question, it is rounding:
但这与问题不符,它是四舍五入:
function cutDecimals(number,decimals){
return number.toLocaleString('fullwide', {maximumFractionDigits:decimals})
}
console.log(
cutDecimals(4.3455,2),
cutDecimals(2.768,2),
cutDecimals(3.67,2)
)
??????
??????
回答by mmgc84
Use toPrecision :)
使用 toPrecision :)
var y = 67537653.76828732668326;
y = (String(y).indexOf('.') !== -1) ? +y.toPrecision(String(y).indexOf('.') + 2) : +y.toFixed(2);
// => 67537653.76
The 2 in the second line dictates the number of decimal places, this approach returns a number, if you want a string remove the "+" operator.
第二行中的 2 表示小数位数,这种方法返回一个数字,如果你想要一个字符串删除“+”运算符。