[英]JavaScript formatting numbers in input by commas not working
我需要用逗號分隔數字,並且我使用了我在這里找到的另一個問題的代碼塊,但它沒有按預期工作
輸入
<input type="text" name="budget" placeholder="Total Budget" class="form-control">
JS
$('input[name=budget]').keyup(function (e) {
e.preventDefault();
let value = $(this).val();
let newValue = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
$(this).val(newValue);
});
當我測試這段代碼時,我遇到了一個問題
我輸入 1000 並正確顯示 1,000
但是當我輸入另一個 0 時,數字返回到這個 1,0,000
我每增加一個 0,它就會在它之后添加一個逗號,就像 1,0,0,0,0,000
您需要先刪除逗號
let newValue = value.toString().replace(/,/g,"").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
有一個用於格式化數字Intl.NumberFormat的本機解決方案
我會使用它,而不是 regExp 替換。
const numberFormatter = new Intl.NumberFormat();
const newValue = numberFormatter.format(value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.