fishbone
fishbone

Reputation: 1

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

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

Upvotes: 0

Views: 375

Answers (2)

ruleboy21
ruleboy21

Reputation: 6391

You can use regular expression. Try this

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

Upvotes: 0

Bikale G
Bikale G

Reputation: 82

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

Upvotes: 1

Related Questions