Making number input in USD currency ($100,000.00)

I have the following code that works fine but doesn’t place a “$” sign or a decimal.

export function input187_input ( event ) {
const input = $w ( ‘#input187’ );
input . onInput ( () => {
input . value = input . value . replace ( /[^0-9,.-]+/ g , ‘’ );
input . value = new Intl . NumberFormat (). format (+ input . value . split ( ‘,’ ). join ( ‘’ ));
})
}

Ideally I would like the hundreds to look like “$100.00” and the thousands to look like “$100,000.00”

Any ideas to edit code and accomplish that?

Appreciate any input.

1 Like

You should use the locale for USD currency.

let number = 1234;//example
const formatted = number.toLocaleString('us-En', {style: 'currency', currency: 'USD'});

How do I implement?

import?

No need to import anything. It’s a JavaScript built-in method.

@jonatandor35

Ok. Sorry but I feel dumb. Where and how do I place the code to make a specific user input show as currency?

@miguelbuyme It depends on what exactly you wish to do.
In my opinion it’s not a good idea to manipulate the user input while they typing because it’s confusing. But if you want it anyway you can put a text input, limits its characters (using regex) to digits, commas, and a leading $ symbol only only.
And do something like:

const input = $w('#input187');
input.onInput(()=> {
const val = Number(input.value.replace('$','').replaceAll(',', ''));
input.value = val.toLocaleString('us-En',{style:'currency', currency:'USD'});
})

@jonatandor35

I hear you. Don’t want to make anything confusing for the user.

I’ll be happy if I can make the currency input to auto populate with a “$”. Is that possible?

Why wouldn’t you just put a text element with the $ sign next to the input element?

This helped me tremendously, thank you! Also, just to add to it a bit. I added in a dollar sign easily by just using a template literal like so:

$ ${ input.value }