我希望最多保留两位小数,但只有必要时才这样做。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
我该如何在JavaScript中实现这个?
我希望最多保留两位小数,但只有必要时才这样做。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
我该如何在JavaScript中实现这个?
最简单的方法:
+num.toFixed(2)
它将数字转换为字符串,然后再转回整数/浮点数。
toFixed()
, 设为 3。这样就是 +num.toFixed(3)
。这样做的效果应该是正确的,1.005 被四舍五入为 1.00,等同于 1。 - bigpotatofunction round(
value,
minimumFractionDigits,
maximumFractionDigits
) {
const formattedValue = value.toLocaleString('en', {
useGrouping: false,
minimumFractionDigits,
maximumFractionDigits
})
return Number(formattedValue)
}
console.log(round(21.891, 2, 3)) // 21.891
console.log(round(1.8, 2)) // 1.8, if you need 1.80, remove the `Number` function. Return directly the `formattedValue`.
console.log(round(21.0001, 0, 1)) // 21
console.log(round(0.875, 3)) // 0.875
使用类似这样的内容 "parseFloat(parseFloat(value).toFixed(2))"
parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78
parseFloat(parseFloat("10").toFixed(2))-->10
parseFloat(parseFloat("9.1").toFixed(2))-->9.1
这里是一个原型方法:
Number.prototype.round = function(places){
places = Math.pow(10, places);
return Math.round(this * places)/places;
}
var yournum = 10.55555;
yournum = yournum.round(2);
为了避免处理许多0,请使用这个变体:
Math.round(num * 1e2) / 1e2
另一种方法是使用库。使用Lodash:
const _ = require("lodash")
const roundedNumber = _.round(originalNumber, 2)
与其像Brian Ustas建议的那样使用Math.round
,我更喜欢使用Math.trunc
方法来解决以下情况:
const twoDecimalRound = num => Math.round(num * 100) / 100;
const twoDecimalTrunc = num => Math.trunc(num * 100) / 100;
console.info(twoDecimalRound(79.996)); // Not desired output: 80;
console.info(twoDecimalTrunc(79.996)); // Desired output: 79.99;
更简单的 ES6 方法是
const round = (x, n) =>
Number(parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n));
这个模式也会返回所要求的精度。
例如:
round(44.7826456, 4) // yields 44.7826
round(78.12, 4) // yields 78.12
78.12
而不是 78.1200
。 - Marcin Wanago> d3.round(1.777777, 2)
1.78
> d3.round(1.7, 2)
1.7
> d3.round(1, 2)
1
我审查了本帖子的每个回答,这是我的看法:
const nbRounds = 7;
const round = (x, n=2) => {
const precision = Math.pow(10, n)
return Math.round((x+Number.EPSILON) * precision ) / precision;
}
let i = 0;
while( nbRounds > i++ ) {
console.log("round(1.00083899, ",i,") > ", round(1.00083899, i))
console.log("round(1.83999305, ",i,") > ", round(1.83999305, i))
}
1.015
(以及其他在其他答案评论中提到的有问题的数字)吗?请通过编辑(更改)您的答案来回复,而不是在这里留言(不要添加“编辑:”,“更新:”或类似内容 - 答案应该看起来像是今天写的)。 - Peter Mortensen
const formattedNumber = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(myNumber); const formattedNumberInNumber = parseFloat(formattedNumber);``` // #=> 1.28。[更多信息](https://dev59.com/anI-5IYBdhLWcg3wsKl4#1726662)
- tinystone