将数字格式化为始终显示两位小数

1225

我想要将数字格式化为始终显示两位小数,必要时要四舍五入。

例如:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

我一直在使用这个:

parseFloat(num).toFixed(2);

但它显示的是1,而不是1.00


2
我指的是如果我输入1,它不会显示为1.00,但是如果我输入1.345,则会显示为1.35。 - Varada
1
我已经重新表述了你的问题,以符合你所寻找的内容。请检查以确保我正确理解了你的意思。 - drudge
精确舍入,支持IE。https://gist.github.com/ArminVieweg/28647e735aa6efaba401 - TarranJones
可能是将数字格式化为两位小数的重复问题。 - ma11hew28
显示剩余2条评论
38个回答

0
在使用JavaScript处理数字时,要小心使用round()、toFixed()等函数,它们会以不同的方式处理数字。source
export const preciseRound = (value, exp) => {
  /**
   * Decimal adjustment of a number.
   *
   * @param   {String}    type    The type of adjustment.
   * @param   {Number}    value   The number.
   * @param   {Integer}   exp     The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number}            The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === "undefined" || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === "number" && exp % 1 === 0)) {
      return NaN;
    }
    // Shift
    value = value.toString().split("e");
    value = Math[type](+(value[0] + "e" + (value[1] ? +value[1] - exp : -exp)));
    // Shift back
    value = value.toString().split("e");
    return +(value[0] + "e" + (value[1] ? +value[1] + exp : exp));
  }

  // You can use floor, ceil or round
  return decimalAdjust("round", value, exp);
};

console.log(preciseRound(1.005, -2));  // <= 1.01
console.log(preciseRound(1.341, -2));  // <= 1.34
console.log(preciseRound(1.01, -2));   // <= 1.01
console.log(preciseRound(33.355, -2)); // <= 33.36

-1
这是我的安全解决方案,它使用epsilion。这将修复.15的舍入问题。
function myFunction(a) {

    return Math.round((a + Number.EPSILON) * 100) / 100
}

-1
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>


<input type="text" class = 'item_price' name="price" min="1.00" placeholder="Enter Price" value="{{ old('price') }}" step="">

<script> 
$(document).ready(function() {
    $('.item_price').mask('00000.00', { reverse: true });
});
</script>

你不需要包含两个庞大且不必要的仅限浏览器的库,响应DOM事件并操作DOM来格式化数字。在发布之前,您应该阅读其他答案中的一些内容。 - Antony Jones

-2
function formatValeurDecimal(valeurAFormate,longueurPartieEntier,longueurPartieDecimal){

valeurAFormate = valeurAFormate.replace(",",".")
valeurAFormate = parseFloat(valeurAFormate).toFixed(longueurPartieDecimal)
if(valeurAFormate == 'NaN'){
    return 0
}

//____________________valeurPartieEntier__________________________________
var valeurPartieEntier = valeurAFormate | 0

var strValeur = valeurPartieEntier.toString()
strValeur = strValeur.substring(0, longueurPartieEntier)
valeurPartieEntier = strValeur

//____________________valeurPartieDecimal__________________________________
strValeur = valeurAFormate
strValeur = strValeur.substring(strValeur.indexOf('.')+1)
var valeurPartieDecimal = strValeur

valeurAFormate = valeurPartieEntier +'.'+valeurPartieDecimal
if(valeurAFormate == null){
    valeurAFormate = 0
}

return valeurAFormate

}


2
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Al Foиce ѫ
1
除了缺少解释之外,该代码使用了法语变量名。 - Mark Lagendijk

-2
你可以尝试这段代码:
    function FormatNumber(number, numberOfDigits = 2) {
        try {
            return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(numberOfDigits));
        } catch (error) {
            return 0;
        }
    }

    var test1 = FormatNumber('1000000.4444');
    alert(test1); // 1,000,000.44

    var test2 = FormatNumber(100000000000.55555555, 4);
    alert(test2); // 100,000,000,000.5556

1
你最好将 toFixed(2) 更改为 toFixed(numberOfDigits) :D - Jurgen Dictus

-3

这是我解决问题的方法:

parseFloat(parseFloat(floatString).toFixed(2));

-3

parseInt(number * 100) / 100; 对我很有用。


-3
(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接