我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
舍入问题可以通过使用指数表示法来避免。
public roundFinancial(amount: number, decimals: number) {
return Number(Math.round(Number(`${amount}e${decimals}`)) + `e-${decimals}`);
}
其他回答
如果您需要将货币金额格式化为整数货币或包含小数货币部分的金额,则会有一点不同。
例如:
1应输出$1
1.1应产出1.10美元
1.01应产出1.01美元
假设金额是一个数字:
常量格式amount=(amount)=>amount%1==0?amount:amount.toFixed(2);
如果amount不是数字,则使用parseFloat(amount)将其转换为数字。
将类型保留为整数,以便以后进行排序或其他算术运算:
Math.round(1.7777777 * 100)/100
1.78
// Round up!
Math.ceil(1.7777777 * 100)/100
1.78
// Round down!
Math.floor(1.7777777 * 100)/100
1.77
或转换为字符串:
(1.7777777).toFixed(2)
"1.77"
const formattedNumber=数学舍入(数字*100)/100;
我读过所有的答案,类似问题的答案和最“好”的解决方案的复杂性都让我不满意。我不想放一个大的圆函数集,或者一个小的圆函数,但在科学记数法上失败了。所以,我想出了这个函数。这可能会对我的处境有所帮助:
function round(num, dec) {
const [sv, ev] = num.toString().split('e');
return Number(Number(Math.round(parseFloat(sv + 'e' + dec)) + 'e-' + dec) + 'e' + (ev || 0));
}
我没有运行任何性能测试,因为我调用它只是为了更新应用程序的UI。该函数为快速测试提供以下结果:
// 1/3563143 = 2.806510993243886e-7
round(1/3563143, 2) // returns `2.81e-7`
round(1.31645, 4) // returns 1.3165
round(-17.3954, 2) // returns -17.4
这对我来说已经足够了。
请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。
var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));