这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?

Math.round(price*Math.pow(10,2))/Math.pow(10,2);

我想要10.80、2.40等数字。jQuery的使用对我来说很好。


当前回答

基于Christian C. Salvadó的答案,执行以下操作将输出一个Number类型,并且似乎也可以很好地处理舍入:

const roundNumberToTwoDecimalPlaces = (num) => Number(new Intl.NumberFormat('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
}).format(num));

roundNumberToTwoDecimalPlaces(1.344); // => 1.34
roundNumberToTwoDecimalPlaces(1.345); // => 1.35

上面提到的与前面提到的不同之处在于,当您使用.format()链接[时,您不需要它,并且它输出一个Number类型]。

其他回答

fun Any.twoDecimalPlaces(numInDouble: Double): String {

    return "%.2f".format(numInDouble)
}

我从几个月前的这篇文章中得到了一些想法,但这里的答案,以及其他文章/博客的答案都不能处理所有的场景(例如负数和我们的测试人员发现的一些“幸运数字”)。最后,我们的测试人员没有发现下面这个方法有任何问题。粘贴我的代码片段:

fixPrecision: function (value) {
    var me = this,
        nan = isNaN(value),
        precision = me.decimalPrecision;

    if (nan || !value) {
        return nan ? '' : value;
    } else if (!me.allowDecimals || precision <= 0) {
        precision = 0;
    }

    //[1]
    //return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
    precision = precision || 0;
    var negMultiplier = value < 0 ? -1 : 1;

    //[2]
    var numWithExp = parseFloat(value + "e" + precision);
    var roundedNum = parseFloat(Math.round(Math.abs(numWithExp)) + 'e-' + precision) * negMultiplier;
    return parseFloat(roundedNum.toFixed(precision));
},

我也有代码注释(对不起,我已经忘记了所有的细节)…我把我的答案贴在这里,以供将来参考:

9.995 * 100 = 999.4999999999999
Whereas 9.995e2 = 999.5
This discrepancy causes Math.round(9.995 * 100) = 999 instead of 1000.
Use e notation instead of multiplying /dividing by Math.Pow(10,precision).

我发现了一个非常简单的方法来解决这个问题,可以使用或适应:

td[row].innerHTML = price.toPrecision(price.toFixed(decimals).length

这是我的1行解决方案:Number((yourNumericValueHere).toFixed(2));

事情是这样的:

1)首先,你将. tofixed(2)应用到你想要四舍五入的小数上。注意,这将把值从number转换为字符串。所以如果你使用Typescript,它会抛出一个这样的错误:

" string类型不能赋值给number类型"

2)要返回数值或将字符串转换为数值,只需对所谓的“字符串”值应用Number()函数。

为了说明问题,请看下面的例子:

例子: 我有一个金额,有高达5位小数,我想缩短到2位小数。我是这样做的:

Var价格= 0.26453; var priceround = Number((价格).toFixed(2)); console.log('原始价格:' +价格); console.log('价格四舍五入:' + pricerounds);

下面是https://stackoverflow.com/a/21323330/916734的TypeScript实现。它还使用了函数,并允许可选的数字偏移量。

export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
  const value = Number(rawValue);
  if (isNaN(value)) return rawValue;

  precision = Number(precision);
  if (precision % 1 !== 0) return NaN;

  let [ stringValue, exponent ] = scientificNotationToParts(value);

  let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
  const enlargedValue = toScientificNotation(stringValue, shiftExponent);
  const roundedValue = Math.round(enlargedValue);

  [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
  const precisionWithOffset = precision + fractionDigitOffset;
  shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);

  return toScientificNotation(stringValue, shiftExponent);
}

enum Shift {
  Left = -1,
  Right = 1,
}

function scientificNotationToParts(value: number): Array<string> {
  const [ stringValue, exponent ] = value.toString().split('e');
  return [ stringValue, exponent ];
}

function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
  precision = shift * precision;
  return exponent ? (Number(exponent) + precision) : precision;
}

function toScientificNotation(value: string, exponent: number): number {
  return Number(`${value}e${exponent}`);
}