gpt4 book ai didi

javascript - 将负值四舍五入到小数点后两位

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:06 25 4
gpt4 key购买 nike

我有两个负值 -0.245-9.085。我想让它们保留到小数点后两位。我正在使用 JavaScript 函数 toFixed() 但得到了一些奇怪的结果。

请帮助我理解第一个示例“向下”舍入而第二个示例“向上”舍入背后的逻辑

//Examples 1. result coming as expected
var num = -0.245
var n = num.toFixed(2); //-0.24
console.log(n);

//Examples 2. result should be -9.08
num = -9.085
n = num.toFixed(2); //-9.09
console.log(n);

最佳答案

根据描述 在 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed提及:

The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

对于-0.245.toFixed(2),该值为负数,小数点后2位为-0.045,-0.045高于-0.05,所以结果四舍五入为-0.24

对于-9.085.toFixed(2),该值为负数,小数点后2位为-0.085,-0.085小于-0.08,所以结果向下取整为-9.09

以下是始终将负值四舍五入到小数点后两位的解决方案。

var num = -9.085
var output = num < 0 ? Math.floor(Math.abs(num) * 100) * -1 / 100 : num.toFixed(2)
console.log(output) //-9.08

关于javascript - 将负值四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com