我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

但是它把1显示为1,而不是1.00。


当前回答

你可以试试下面的代码:

    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

其他回答

你没有告诉我们全部情况。

alert(parseFloat(1). tofixed(2))显示1.00在我的浏览器,当我粘贴到位置栏。 然而,如果你事后对它做了一些事情,它就会恢复。

alert(parseFloat(1).toFixed(2)) 变量数 = 2 document.getElementById('spanId').innerHTML = (parseFloat(num).toFixed(2) - 1) <span id=“spanId”></span>

shows 1 and not 1.00
Number(1).toFixed(2);         // 1.00
Number(1.341).toFixed(2);     // 1.34
Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35

. getelementbyid(“line1”)。innerHTML = Number(1).toFixed(2); . getelementbyid(么)。innerHTML = Number(1.341).toFixed(2); . getelementbyid(“line3”)。innerHTML = Number(1.345).toFixed(2); . getelementbyid(“line4”)。innerHTML = Number(1.3450001).toFixed(2); < span id = " line1 " > < / span > < br / > < span id = "么" > < / span > < br / > < span id = " line3 " > < / span > < br / > < span id = " line4 " > < / span >

<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>

function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){ var numbers = string.toString().match(/\d+/g).join([]); numbers = numbers.padStart(decimals+1, "0"); var splitNumbers = numbers.split("").reverse(); var mask = ''; splitNumbers.forEach(function(d,i){ if (i == decimals) { mask = decimal + mask; } if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; } mask = d + mask; }); return pre + mask + pos; } var element = document.getElementById("format"); var money= number_format("10987654321",2,',','.'); element.innerHTML = money; #format{ display:inline-block; padding:10px; border:1px solid #ddd; background:#f5f5f5; } <div id='format'>Test 123456789</div>

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