我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

在Node.js环境中,我只使用roundTo模块:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

其他回答

这对我(TypeScript)起到了作用:

round(decimal: number, decimalPoints: number): number{
    let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);

    console.log(`Rounded ${decimal} to ${roundedValue}`);
    return roundedValue;
}

样本输出

Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28

有一种解决方案适用于所有数字。试试看。表达式如下所示。

Math.round((num + 0.00001) * 100) / 100. 

Try Below Ex:

Math.round((1.005 + 0.00001) * 100) / 100 
Math.round((1.0049 + 0.00001) * 100) / 100

我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。

这是计算过程中出现的问题的屏幕截图,

.

转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。

如果您需要将货币金额格式化为整数货币或包含小数货币部分的金额,则会有一点不同。

例如:

1应输出$1

1.1应产出1.10美元

1.01应产出1.01美元

假设金额是一个数字:

常量格式amount=(amount)=>amount%1==0?amount:amount.toFixed(2);

如果amount不是数字,则使用parseFloat(amount)将其转换为数字。

具有可读选项的函数更直观:

function round_number(options) {
    const places = 10**options.decimal_places;
    const res = Math.round(options.number * places)/places;
    return(res)
}

用法:

round_number({
    number : 0.5555555555555556,
    decimal_places : 3
})

0.556

当我想一直舍入到某个小数点时,这对我来说非常有效。这里的关键是,我们将始终使用Math.ceil函数进行舍入。

如果需要,可以有条件地选择天花板或地板。

/***在大量数据时可能失去精度*@param编号*@return数字*/var roundUpToNearestHundredth=函数(数字){//确保我们使用高精度数字number=数量(number);//保存原始数字,这样当我们提取第一百位小数时,就不会进行位切换或丢失精度var numberSave=数字(Number.toFixed(0));//删除数字顶部的“整数”值number=number-number保存;//获取小数点后一百位数量*=100;//终止小数。因此,15000001将等于151等。number=数学ceil(数字);//把小数放回正确的位置数量/=100;//将“整数”加回到数字上return number+numberSave;};console.log(roundUpToNearestHundredth(6132423.1200000000001))