获取 2 位浮点数未按预期工作

Getting 2 digits floating number isn't working as expected

本文关键字:工作 浮点数 获取      更新时间:2023-09-26

>我有这个数字:-0.0166667,我只想得到两个浮点数,所以数字应该是-0.01

我试过这个

-0.0166667.toFixed(2)  # gives : -0.02

还有这个

Math.round(-0.0166667 * 100) / 100 # also gives : -0.02

但是他们都将数字转换为-0.02而不是-0.01

这是怎么回事?

按位|或截断分数部分。

var x = (-0.0166667 * 100 | 0) / 100,
    y = (0.0166667 * 100 | 0) / 100;
document.write(x + '<br>' + y);

一个更好的解决方案,可以保存标志,应用地板并将标志放回原处。

function toFixed(x, digits) {
    return (x < 0 ? - 1 : 1) * Math.floor(Math.abs(x) * Math.pow(10, digits)) / Math.pow(10, digits);
}
document.write(toFixed(-0.0166667, 2) + '<br>');
document.write(toFixed(0.0166667, 2) + '<br>');
document.write(toFixed(-0.0166667, 3) + '<br>');
document.write(toFixed(0.0166667, 3) + '<br>');

Math.round会将数字四舍五入到最接近的整数,因此代码的输出实际上是正确的。您需要的是截断而不是舍入。这是最简单的方法:

function toZero(x) {
  return x > 0 ? Math.floor(x) : Math.ceil(x);
}
function round2digits(x) {
  return toZero(x * 100) / 100;
}
document.write(round2digits(-0.0166)); // prints `-0.01`

对于小于零之间的数字,Math.ceil截断而不舍入,对于大于零的数字Math.floor工作正常。由于您的数字小于 zer,因此请使用Math.ceil

Math.ceil(-0.0166667 * 100) / 100

编辑

编写自定义帮助程序方法来截断浮点

function truncate(num) {
    return num > 0 ? Math.floor(num) : Math.ceil(num);
}

并将数字四舍五入 2 位数字使用

truncate(num * 100) / 100