html 用户键入数字时添加逗号(例如:1,000/10,000/100,000/1,000,000/10,000,000等

jchrr9hc  于 2023-03-11  发布在  其他
关注(0)|答案(2)|浏览(364)

我是一个新手。我做了研究,并能够写这个代码,工作得很好。唯一的问题是,当用户键入金额没有逗号分隔千,百万等。有人有任何想法修改或添加一些代码,使当用户键入数字的逗号自动添加?见下面的代码和截图。

$w.onReady(function () {
    $w("#input247").onChange((Event) => {

let price = Number($w('#input247').value);
let traditionalPercent = Number ($w('#text556').text);
let buyersAgentPercent = Number ($w('#text557').text);
 

$w("#input247").value = null;

$w('#text548').text = '$' + price.toLocaleString();
$w('#text549').text = '$' + (price * traditionalPercent).toLocaleString();
$w('#text550').text = '$' + (price * buyersAgentPercent).toLocaleString();
$w('#text551').text = '$' + (price * traditionalPercent - price * buyersAgentPercent).toLocaleString();
    
    })})

screenshot

ac1kyiln

ac1kyiln1#

您可以使用javascript Intl.NumberFormat国际化API

let sale1 = 2500;
let sale2 = 762500;
let sale3 = 20660055500;
console.log(new Intl.NumberFormat().format(sale1));
console.log(new Intl.NumberFormat().format(sale2));
console.log(new Intl.NumberFormat().format(sale3));

查看更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

7xzttuei

7xzttuei2#

您可以使用正则表达式。请尝试以下操作

let numberFormat = (number) => parseFloat(number).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
console.log(numberFormat(1000000));

相关问题