在 JavaScript 中获得两位小数而不四舍五入到下一个更大的数字

Obtain two decimal places in JavaScript without rounding to the next bigger number

我有这个 JS 代码:

var propertyYield = annualRent / propertyValue * 100.0;

在特定情况下,结果为 4.999。

所以当我这样做时

propertyYield.toFixed(2)

我的 propertyYield 为 5.00。

我想要实现的是实际得到 4.99 而不是 5.00 四舍五入到两位小数。

我怎样才能做到这一点?

更新:正如@kuka 所指出的,由于浮点运算错误,这不适用于某些十进​​制数。不要使用此解决方案 - 但是为了文档起见,我将其保留在这里。

不确定我是否知道现有的库方法可以做到这一点,但快速简单的老式解决方案是这样的:

Math.floor(4.999 * 100) / 100.0

您可以使用 Math.floor 和一些额外的算法:

Math.floor(15.7784514000 * 100) / 100

或者把数字转成字符串,匹配到小数点后第二位再转回数字:

Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))

那你还是可以调用toFixed得到固定小数位数的字符串

var num1 = Math.floor(15.7784514000 * 100) / 100;
console.log(num1);

var num2 = Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/));
console.log(num2)
console.log(num2.toFixed(2))