[英]Convert String with Dot or Comma as decimal separator to number in JavaScript
[英]How to convert a number where I replaced the dot with a comma from a string back to a decimal number
我有一個輸入字段,用戶可以使用點或逗號輸入十進制數字(例如:79,99或79.99)。 當用戶使用逗號輸入數字時,我將其替換為點(此數字隨后會發送到遠程服務器進行驗證)。 現在我想在用戶使用toFixed(2)函數在頁腳中輸入數字后顯示數字,只顯示前兩個十進制數字。 我無法使它工作,因為在使用ParseFloat將其轉換回數字之后,逗號消失后的2位小數。
例:
用戶輸入輸入字段:79,99然后將其設置為變量totalAmount:
$('#amount-1').keyup(function() {
getRefundAmount(1); // This function calls the calcTotalAmount function
})
function calcTotalAmount() {
console.log('calcTotalAmount');
var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;
for(var i = 1; i < 4; i++ ) {
rowAmount = parseFloat($('#amount-' + i).val());
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);
$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
$('#footer-total').text("0.00");
}
}
頁腳中顯示的結果為:79.00而不是79.99
我在jsfiddle中嘗試了你的代碼並在“.toFixed(2)”上得到了一個錯誤。更改它后我可以防止錯誤:
$(function() {
var totalAmount = '79,99';
totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
totalAmount = totalAmount.toFixed(2);
$('#footer-refund').text(totalAmount)
});
看起來你給出的代碼工作得很好但是你可以應用一些修復:
totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues
順便說一句,你做$('#footer-refund').text(totalRefund.toFixed(2))
,不應該是$("#footer-refund").text(totalAmount)
(不知道為什么你用toFixed這里也) ?
感謝您的幫助:
解決方案如下:我必須在for循環中檢查它並在那里替換它。
for(var i = 1; i < 4; i++ ) {
if(!$('#amount-' + i).val()){continue;}else{
rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.