I want to get a string of numbers and add mas to create a more readable format for a long number. Normally I'd use toLocaleString()
but it's not working as expected with a controlled input.
In my code I'm doing:
handleChange(event) {
const parseNumber = parseInt(event.target.value);
const toLocale = parseNumber.toLocaleString();
this.setState({ value: toLocale });
}
It's resetting the field after 3 numbers are entered - any ideas?
I want to get a string of numbers and add mas to create a more readable format for a long number. Normally I'd use toLocaleString()
but it's not working as expected with a controlled input.
In my code I'm doing:
handleChange(event) {
const parseNumber = parseInt(event.target.value);
const toLocale = parseNumber.toLocaleString();
this.setState({ value: toLocale });
}
It's resetting the field after 3 numbers are entered - any ideas?
https://codesandbox.io/s/91q75k22mo
Share Improve this question asked Mar 14, 2018 at 10:59 Paul RedmondPaul Redmond 3,2964 gold badges35 silver badges53 bronze badges 1- I think this is like an issue of react. github./facebook/react/issues/6368 – Heartbit Commented Mar 14, 2018 at 11:27
2 Answers
Reset to default 5Working solution - in your handleChange function, change this:
const toNumber = Number(event.target.value);
to this:
const toNumber = Number(event.target.value.replace(/\D/g, ''));
The reason it wasn't working was because it was creating a Number
based on the input value, which isn't a plain number but a formatted string. Hence it contains non-digit characters. The above just removes the non-digit characters (though now you know the issue there are other ways you could solve it).
You can use FormattedNumber
from react-intl
. The documentation is available here: https://github./yahoo/react-intl/wiki/Components#number-formatting-ponents
A sample:
<IntlProvider locale='en'>
<FormattedNumber value={examples.negativeNumber} />
</IntlProvider>