This question already has answers here:
Round to at most 2 decimal places (only if necessary)

(80个答案)


3年前关闭。




我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);

这四舍五入为整数。如何返回两位小数的结果?

最佳答案

注-如果3位精度很重要,请参阅编辑4

var discount = (price / listprice).toFixed(2);
toFixed将为您舍入或舍入,具体取决于小数点后2位的值。
示例:http://jsfiddle.net/calder12/tv9HY/
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
编辑-如其他人所述,它将结果转换为字符串。为了避免这种情况:
var discount = +((price / listprice).toFixed(2));
编辑2 -正如注释中所提到的,此函数在某种程度上会失败,例如在1.005的情况下,它将返回1.00而不是1.01。如果达到这个程度的准确性很重要,那么我会找到以下答案:https://stackoverflow.com/a/32605063/1726511这似乎对我尝试过的所有测试都有效。
但是,需要进行一些小的修改,上面链接的答案中的函数在四舍五入时返回整数,因此例如99.004将返回99而不是99.00,这对于显示价格而言并不理想。
编辑3 -似乎在实际 yield 表上固定了toill仍在搞砸一些数字,此最终编辑似乎有效。哎呀,这么多返工!
var discount = roundTo((price / listprice), 2);

function roundTo(n, digits) {
  if (digits === undefined) {
    digits = 0;
  }

  var multiplicator = Math.pow(10, digits);
  n = parseFloat((n * multiplicator).toFixed(11));
  var test =(Math.round(n) / multiplicator);
  return +(test.toFixed(digits));
}
请参阅此处的 fiddle 示例:https://jsfiddle.net/calder12/3Lbhfy5s/
编辑4 -你们杀了我。 Edit 3对负数失败,而没有深入研究为什么在进行舍入之前将负数变为正数更容易处理,然后在返回结果之前将其变回正好。
function roundTo(n, digits) {
    var negative = false;
    if (digits === undefined) {
        digits = 0;
    }
    if (n < 0) {
        negative = true;
        n = n * -1;
    }
    var multiplicator = Math.pow(10, digits);
    n = parseFloat((n * multiplicator).toFixed(11));
    n = (Math.round(n) / multiplicator).toFixed(digits);
    if (negative) {
        n = (n * -1).toFixed(digits);
    }
    return n;
}
fiddle :https://jsfiddle.net/3Lbhfy5s/79/

关于javascript - JavaScript数学,四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15762768/

10-12 00:22
查看更多