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

JavascriptParsingNumber Formatting

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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/

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

var number = 3500;

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

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

var converted = parseInt(formatted)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2754545View Question on Stackoverflow
Solution 1 - JavascriptPriyank ShethView Answer on Stackoverflow
Solution 2 - JavascriptSalarenkoView Answer on Stackoverflow
Solution 3 - Javascripto--oOoOoO--oView Answer on Stackoverflow
Solution 4 - JavascriptCodeblingView Answer on Stackoverflow
Solution 5 - JavascriptFrédéric MarchalView Answer on Stackoverflow
Solution 6 - JavascriptSatheeshView Answer on Stackoverflow
Solution 7 - Javascriptuser11849266View Answer on Stackoverflow