If I do:
var number = 35000.25; alert(number.toLocaleString("de-DE"));
I will get 35.000,25
in German.
But how can I convert it back to 35000.25
or I want something like:
var str='35.000,25'; alert(str.toLocaleNumber("en-US"));
So, that it can give 35,000.25
.
Is it possible by JS?
If I do:
var number = 35000.25; alert(number.toLocaleString("de-DE"));
I will get 35.000,25
in German.
But how can I convert it back to 35000.25
or I want something like:
var str='35.000,25'; alert(str.toLocaleNumber("en-US"));
So, that it can give 35,000.25
.
Is it possible by JS?
Share Improve this question edited Oct 19, 2018 at 11:10 niclas_4 3,6741 gold badge24 silver badges51 bronze badges asked Oct 19, 2018 at 11:05 Srinivasan GSrinivasan G 351 silver badge5 bronze badges 3- 3 Possible duplicate of How do I convert String to Number according to locale (opposite of .toLocaleString)? – briosheje Commented Oct 19, 2018 at 11:10
- no , I am looking different solution – Srinivasan G Commented Oct 19, 2018 at 11:14
- 2 Well then explain different how? – misorude Commented Oct 19, 2018 at 11:19
2 Answers
Reset to default 5The following function will first construct a NumberFormat based on the given locale. Then it will try to find the decimal separator for that language.
Finally it will replace all but the decimal separator in the given string, then replace the locale-dependant separator with the default dot and convert it into a number.
function convertNumber(num, locale) {
const { format } = new Intl.NumberFormat(locale);
const [, decimalSign] = /^0(.)1$/.exec(format(0.1));
return +num
.replace(new RegExp(`[^${decimalSign}\\d]`, 'g'), '')
.replace(decimalSign, '.');
}
// convertNumber('100,45', 'de-DE')
// -> 100.45
Keep in mind that this is just a quick proof of concept and might / will fail with more exotic locales that do not follow the assumptions made here (e.g. left-to-right, no weird number insertions, no whitespace, no signs etc.).
You can however adapt this...
I know this is a bit late, but future readers may find this helpful. My team and I had the exact same problem a couple of months ago, where we needed to convert strings to numbers in more "exotic" locales, such as Indian, in a generic way. So, we've created a basic Javascript library that does exactly that and open-sourced it. It's called locale-to-number.js
and you can find it here: https://github./fromScratchStudioGr/locale-to-number.js.
It, currently, supports most of the available locales, while the rest of them are about to be implemented as well.
Cheers!