簡體   English   中英

JS - 格式編號,帶小數點后2位未舍入

[英]JS - Format number with 2 decimal not rounded

我會格式化一個2位小數的數字而不進行舍入。 所以我排除了toFixed()函數。

我試過這種方式

a = 1,809999
b = 27,94989

a = Math.floor(a * 100) / 100; --> 1,8
b = Math.floor(b * 100) / 100; --> 27,94

OR

a = Number(a.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 1,8
b = Number(b.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 27,94

不幸的是,a的第二個小數是零,這被刪除了,我怎么能保持它並且= 1.80? 謝謝

(Math.floor(a * 100) / 100).toFixed(2);

用toFixed(2)!

JSFIDDLE DEMO

你可以嘗試這樣:

a= a.toString().slice(0, (a.indexOf("."))+3); 

JSFIDDLE DEMO

舍入數字是關於改變它的值,應該用數學運算完成(Math.floor,Math.ceil,Math.round,...)。

格式化編號,是關於如何向人類用戶顯示數字(如日期格式)。

Javascript沒有可接受的本機工具來進行數字格式化。

您可以隨時使用舍入來使javascript以您想要的方式打印數字,但最終會編寫很多(可能是錯誤的)代碼。

我建議使用庫格式化您的數字http://numeraljs.com/

numeral(number).format('0.00');

只需要使用toFixed()並將數字傳遞為2然后顯示之后。 兩個十進制像bello

a = 1,809999
b = 27,94989

a = Math.floor(a * 100) / 100; 
b = Math.floor(b * 100) / 100; 

$(".testa").text(a.toFixed(2)); //see here.
$(".testb").text(b.toFixed(2)); //see here.

Html:

<div class="testa"></div>
<br>
    <div class="testb"></div>

我希望這能幫到您。 並且還看到這個jsfiddle鏈接http://jsfiddle.net/RGerb/394/

myFunction(value: number){
let x = value + ''; 
  var a =  x.lastIndexOf('.')>=0?parseFloat(x.substr(0,x.lastIndexOf('.')+(3))):value;
  var am = a.toFixed(2)
  console.log("Output: " + am);
  return am;

}

<button (click)="myFunction(656565.9668985)">My Function</button>

Output: 656565.96

暫無
暫無

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

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