簡體   English   中英

將數字格式化為最后兩位小數

[英]Format number to last two decimals

我正在嘗試將 JS 中的數字格式化為最后兩位小數。

例如 10100 變為 101.00 - 606000 變為 6,060.00 - 7600 變為 76.00 等等。

我試過 num.toFixed(2) 但這沒有幫助。 我也嘗試過Number(10100).toLocaleString("es-ES", {minimumFractionDigits: 0})但我最終得到 10.100,所以它看起來少了一位。

所以

num.toFixed(2) 

它的格式是什么,這將是 10.123 -> 10.12

你應該做的是將數字除以 100。

var number = 10100
number = number / 100

將是你需要的。

最簡化的方法:

output = (number/100).toFixed(2)

以及復雜的方式:

var c = 7383884
a = c.toString()
var output = parseFloat([a.slice(0, -2), ".",a.slice(-2)].join(''))

document.write(output)

我將通過使用strings的幫助來解決這個問題。

字符串可以根據我們的要求輕松操作,然后可以轉換回數字。 所以,解決方案是這樣的

  1. 將數字轉換為字符串
  2. 操作字符串以在最后兩個字符之前添加小數
  3. 將字符串轉換回數字

 const formatNumberToLastTwoDecimal = (number) => { // Convert the number to String const inputNumAsStr = number.toString(); // Manipulate the string and add decimal before two char const updatedStr = `${inputNumAsStr.slice(0, -2)}.${inputNumAsStr.slice(-2)}`; // Return by converting the string to number again // Fix by 2 to stop parseFloat() from stripping zeroes to right of decimal return new Number(parseFloat(updatedStr)).toFixed(2); } console.log(formatNumberToLastTwoDecimal(606000));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM