How do I convert String to Number according to locale (opposite of .toLocaleString)?
Asked Answered
S

7

70

If I do:

var number = 3500;
alert(number.toLocaleString("hi-IN"));

I will get ३,५०० in Hindi.

But how can I convert it back to 3500. I want something like:

var str='३,५००';
alert(str.toLocaleNumber("en-US"));

So, that it can give 3500.

Is it possible by javascript or jquery?

Skees answered 3/9, 2014 at 13:5 Comment(7)
The result of 3500 in format of 'en-Us' would be 3,500Rileyrilievo
Well numbers are just numbers, so there is no en-US number. The real question is how to parse a string from a different locale. So something like parseIntFromLocale. There are lots of number formatting and parsing libraries out there, I'm sure one must support Hindi. I don't think there's anything native in javascript for this.Gers
It doesn't take care of the thousand and decimal separators, but have a look at JavaScript can't convert Hindi/Arabic numbers to real numeric variablesMoriarty
I've used this jquery plugin before jquery.numberformatter and it claims to support the in locale (although I've never tried it). It would let you do something like: $.parseNumber(str, {format:"#,###", locale:"in"});Gers
$.parseNumber(str, {format:"#,###", locale:"in"}); haven't helped for '३,५००'Skees
an alternative solution I use to solve in some scenarios like sorting grid rows or calculating totals dinamically is to store the raw value in the Html element as in <div data-rawvalue="12345.67">12.345,67 €</div>Celibate
See this related post.Impracticable
C
6

I think you are looking for something like:

https://github.com/jquery/globalize

Above link will take you to git project page. This is a js library contributed by Microsoft. You should give it one try and try to use formt method of that plugin. If you want to study this plugin, here is the link for the same:

http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft

I hope this is what you are looking for and will resolve your problem soon. If it doesn't work, let me know.

Cyzicus answered 24/9, 2014 at 12:23 Comment(1)
Globalize is great and is the best way to do this. See example usage hereYong
E
4

Recently I've been struggling with the same problem of converting stringified number formatted in any locale back to the number.

I've got inspired by the solution implemented in NG Prime InputNumber component. They use Intl.NumberFormat.prototype.format() (which I recommend) to format the value to locale string, and then create set of RegExp expressions based on simple samples so they can cut off particular expressions from formatted string.

This solution can be simplified with using Intl.Numberformat.prototype.formatToParts(). This method returns information about grouping/decimal/currency and all the other separators used to format your value in particular locale, so you can easily clear them out of previously formatted string. It seems to be the easiest solution, that will cover all cases, but you must know in what locale the value has been previously formatted.

Why Ng Prime didn't go this way? I think its because Intl.Numberformat.prototype.formatToParts() does not support IE11, or perhaps there is something else I didn't notice.

A complete code example using this solution can be found here.

Ewold answered 2/7, 2020 at 10:24 Comment(1)
I was about to write this as an answer, as I just recently struggled with this. Instead I just added a link here to a complete code example.Accusation
Y
2

Use the Globalize library.

Install it

npm install globalize cldr-data --save

then

var cldr = require("cldr-data");
var Globalize = require("globalize");

Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));

//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));

//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());

//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See 
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension 
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');

var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");

console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500));   //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००

https://github.com/codebling/globalize-example

Yong answered 8/8, 2016 at 6:15 Comment(2)
Identical answer to top one, which was made 2 years before this one wasFarmer
@Farmer kinda? Fair point that it references the same library, but my answer provides a solution to the question, whereas the top answer only provides two links which "may help". While I have upvoted that answer, it really isn't any better than a recommendation of "here's a resource which might help". I thought link-only answers are not generally considered acceptable, but you're the one with all of the rep. One could argue that I should have added my answer to the top one, but we're all just here for the magical internet points, aren't we?Yong
D
1

Unfortunately you will have to tackle the localisation manually. Inspired by this answer , I created a function that will manually replace the Hindi numbers:

function parseHindi(str) {
    return Number(str.replace(/[०१२३४५६७८९]/g, function (d) {
        return d.charCodeAt(0) - 2406;
    }).replace(/[०१२३४५६७८९]/g, function (d) {
        return d.charCodeAt(0) - 2415;
    }));
}

alert(parseHindi("३५००"));

Fiddle here: http://jsfiddle.net/yyxgxav4/

Dogmatic answered 3/9, 2014 at 16:52 Comment(2)
Thanks a lot. But I am in situation where I have to convert numbers in any language in english as my application have to support supports all possible cultures.Skees
You will have to do one at a time then for languages with non-latin characters. I've worked on many localised projects and unfortunately there isn't such a thing as an "universal translator".Dogmatic
L
0

You can try this out

function ConvertDigits(input, source, target) {
var systems = {
    arabic: 48, english: 48, tamil: 3046, kannada: 3302, telugu: 3174, hindi: 2406,
    malayalam: 3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
},
output = [], offset = 0, zero = 0, nine = 0, char = 0;
source = source.toLowerCase();
target = target.toLowerCase();

if (!(source in systems && target in systems) || input == null || typeof input == "undefined" || typeof input == "object") {
    return input;
}

input = input.toString();
offset = systems[target] - systems[source];
zero = systems[source];
nine = systems[source] + 9;    
for (var i = 0 ; i < input.length; i++) {
    var char = input.charCodeAt(i);
    if (char >= zero && char <= nine) {
        output.push(String.fromCharCode(char + offset));
    } else {
        output.push(input[i]);
    }
}
return output.join("");

}

var res = ConvertDigits('१२३४५६७८९', 'hindi', 'english');

I got it from here If you need a jquery thing then please try this link

Lieutenant answered 19/9, 2014 at 7:22 Comment(1)
I don't think this handles the various locale dependent ways to do either thousands or lakh/crore separators, which is much more common in toLocaleString results than different digit characters.Millstream
S
0

A common scenario for this problem is to display a float number to the user and then want it back as a numerical value.

In that case, javascript has the number in the first place and looses it when formatting it for display. A simple workaround for the parsing is to store the real float value along with the formatted value:

var number = 3500;
div.innerHTML = number.toLocaleString("hi-IN");
div.dataset.value = number;

Then get it back by parsing the data attribute:

var number = parseFloat(div.dataset.value);

This is a Columbus's egg style answer. It works provided the problem is an egg.

Solana answered 3/7, 2020 at 4:42 Comment(0)
U
-1
var number = 3500;

var toLocaleString = number.toLocaleString("hi-IN")

var formatted = toLocaleString.replace(',','')

var converted = parseInt(formatted)
Uxorial answered 28/7, 2019 at 19:15 Comment(3)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Enlarger
This is the opposite of the requested question. The question requests how to convert localized String to a Number. Not Number to localized String.Meridethmeridian
This doesn't work for locales where ',' is the decimal separator, such as Germany and many other European locales en.wikipedia.org/wiki/…Outwear

© 2022 - 2024 — McMap. All rights reserved.