我已經瀏覽了無數的線程在這裏和其他地方超過2天,我無法得到這個工作正常。適當的JS貨幣格式,逗號和小數
我有一臺計算器正好按照我需要的方式工作,但是,我似乎無法完成最後一件事情。用逗號隔開的逗號分隔符。
我有小數位,但不能加逗號。當我添加逗號時,可以在計算中斷之前讓一個或兩個字段工作,或者將值顯示爲NaN。
這裏的工作頁面:http://codepen.io/anon/pen/Fauzy
它目前使用這個:
function FormatAsMoney(mnt) {
mnt -= 0;
mnt = (Math.round(mnt*100))/100;
return (mnt == Math.floor(mnt)) ? mnt + '.00'
: ((mnt*10 == Math.floor(mnt*10)) ?
mnt + '0' : mnt);
}
如果我嘗試使用此:
function FormatAsMoney(x)
{
var money_value;
mnt = x.value;
mnt = mnt.replace(/\,/g,'');
mnt -= 0;
mnt = (Math.round(mnt*100))/100;
money_value = (mnt == Math.floor(mnt)) ? mnt + '.00' : ((mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
if (isNaN(money_value))
{
money_value ="0.00";
}else{
money_value = CommaFormatted(money_value);
x.value = money_value.replace(".00", "");
}
}
它不會在所有的工作。
我沒有使用其他測試:
function FormatAsMoney(str) {
return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
在我得到逗號的第一個字段的格式,但失去小數和它不會繼續任何其他計算。
另一個例子我創建了另一個函數中添加逗號,如:
function addCommas(nStr){
nStr += '';
c = nStr.split(','); // Split the result on commas
nStr = c.join(''); // Make it back to a string without the commas
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
然後我用它喜歡:
document.Rate.RATE.value=addCommas(FormatAsMoney(dasum));
這似乎是我一直還沒有最好的結局,但是在線(163),例如,function dosum()
依賴於許多if語句,它再次打破。我似乎無法讓它適用於價值將達到數千的所有應用領域。
我需要能夠輸入頂部2000萬美元「20000000」的「保險金額」(作爲一個例子,因爲它將填充幾乎所有可能的字段,將有一個逗號分隔的小數點位置)
任何人都可以結束我的苦難嗎?謝謝你的幫助。
你是說沒有在[個方法是問題](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript)工作?擁有超過450票的人似乎在測試後很快就能正常工作。 – numbers1311407
還有[toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) – numbers1311407