2017-04-03 33 views
0

因此,從閱讀周圍我知道我應該將整數(1078美分)表示爲美元金額(如$ 10.78)。在javascript貨幣字符串中轉換十進制的最佳方式

My apps input is sometimes pretty ugly. Stuff like "$10.78533999". I know I can use parseFloat + Math.round like so: 

返回Math.round(100 * parseFloat(dollarsAndCentsString.replace(/ [$,] /克, '')));

但我很擔心舍入誤差。我可以做一些複雜的是這樣的:

Number.prototype.round = function(places){ 
    places = Math.pow(10, places); 
    return Math.round((this + Number.EPSILON) * places)/100; 
} 

var shiftDecimal = function(amount){ 
    var amountDecPos = amount.indexOf('.'); 
    var intAmount = amount.substring(0, amount.indexOf('.')); 
    var remainder = parseFloat(amount.substring(amount.indexOf('.') , amount.length)).round(2).toString().substr(2); 
    return intAmount + remainder; 
} 

https://jsfiddle.net/eg0as88b/1/

在那裏我有一個自定義的(我認爲很準確)取整函數,僅在小數運營商,以儘量減少舍入誤差。

這是矯枉過正?它似乎應該有一個更好的方式(特別是性能明智)。謝謝!

+0

你說的是爲了顯示或存儲與計算域的目的?舍入的重要性取決於您的場景。 – Paul

回答

0

最好的方法是使用number.toLocaleString()函數。

這是JavaScript給出的將數字轉換爲貨幣的內置函數。

Ex。

var number = 10.78533999; 

console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2})); // Displays "10.79" if in U.S. English locale 

參考鏈接:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

+0

這似乎工作,當我試圖擺脫小數(我不得不使用toFixed(0))時有點麻煩。我是否需要擔心如何使用本地字符串?這是一個JSFiddle的整個事情: https://jsfiddle.net/xcrc09L4/3/ –

+0

你不需要擔心toLocalString輪。如果我的解決方案爲你工作,那麼請回答我的答案。 &也是答案。所以其他你知道這個答案是正確的 –

相關問題