matteog
matteog

Reputation: 190

React-native set number to string by locale

I have a number, if I use the amount.toFixed() I get this string "100.00". I want the result to be consistent with the locale.

if locale is Italian the result is 100,00 , if locale is English the result is 100.00

what can I use?

amount.toFixed(2)

I use react-native

Upvotes: 0

Views: 4179

Answers (2)

Tim
Tim

Reputation: 10709

You should use directly the javascript built-in method Intl​.Number​Format. There are many useful properties.

To format your number, you can use the properties maximumSignificantDigits, minimumSignificantDigits, maximumFractionDigits, minimumFractionDigits and minimumIntegerDigits.

Here is a working fiddle:

var number = "123456.78"; // string 

console.log(new Intl.NumberFormat('de-DE', { style: 'decimal'}).format(number));

console.log(new Intl.NumberFormat('en-US', { style: 'decimal', maximumSignificantDigits:7 }).format(number));

Upvotes: 2

Alex
Alex

Reputation: 878

Javascript has a built-in function for this, Intl.NumberFormat:

const updateNr = (val: any) => {
var formatter = new Intl.NumberFormat("it-IT");         
updateValue(formatter.format(val.replace(/,/g, "")));   //Remove ',' to format number again
};

Or you can use the react-number-format plugin if you are using React.

Upvotes: 0

Related Questions