【问题标题】:javascript rounding numbers to two decimal places [duplicate]javascript将数字四舍五入到小数点后两位[重复]
【发布时间】:2018-08-16 16:28:00
【问题描述】:

谁能告诉我如何在 javascript 中实现这种类型的舍入:

95.123 => 95.13
95.120 => 95.12
95.129 => 95.13
124.121 => 124.13

感谢您的帮助。

一个

【问题讨论】:

  • 95.123 如何“四舍五入”为95.13124.121124.13
  • 您要四舍五入还是向上舍入?
  • 你已经尝试了什么?你为什么要这样四舍五入?背景对于回答您的问题至关重要。 How do I ask a good question?
  • 如果您仅出于显示目的进行舍入,请使用toFixed():stackoverflow.com/questions/3163070/…

标签: javascript


【解决方案1】:

使用Math.ceil(num * 100) / 100

console.log(Math.ceil(95.123 * 100) / 100);
console.log(Math.ceil(95.120 * 100) / 100);
console.log(Math.ceil(95.129 * 100) / 100);
console.log(Math.ceil(124.121 * 100) / 100);

【讨论】:

  • 谢谢卡兰,正是我想要的。
【解决方案2】:

一种快速简便的方法是乘以 100,四舍五入,然后除以 100。

let value = 95.123;
let rounded = Math.round(value * 100) / 100;

另一种选择是使用Number.toFixed()(这里要小心,因为toFixed() 返回的是字符串,而不是数字)。

let value = 95.123;
let rounded = Number((value).toFixed(2));

一个稍微花哨的方法是使用指数符号。

let value = 95.123;
let rounded = Number(Math.round(value+'e2')+'e-2');

这可以重构为一个辅助函数来处理不同的十进制值。

function roundToDec(value, decimals) {
  let posExp = 'e' + decimals;
  let negExp = 'e-' + decimals;
  return Number(Math.round(value + posExp) + negExp);
}

let value = 95.123;
let rounded = roundToDec(value, 2);

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多