Home > Software engineering >  Adding comma as user types number (Ex: 1,000 / 10,000 / 100,000 / 1,000,000 / 10,000,000 etc
Adding comma as user types number (Ex: 1,000 / 10,000 / 100,000 / 1,000,000 / 10,000,000 etc

Time:12-31

I'm a novice. I did research and was able to write this code that works great. The only issue is that when the user types the amount there are no commas separating the thousands, millions, etc. Does anyone have any ideas on modifying or adding something to code so that when the user types numbers the commas are added automatically? See code and screenshot below.

$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

CodePudding user response:

You can use javascript Intl.NumberFormat Internationalization 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));

for more info checkout https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

CodePudding user response:

You can use below function.

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

So numberFormat(1000000) // 1,000,000.00

  • Related