Format number with jQuery Globalize

don picture don · May 26, 2013 · Viewed 20.4k times · Source

I'm trying to automatically format a number with the proper localization with Globalize. When the users inputs a numeric value I need Globalize to read it, parse it in the right format, and then output it in the field where the user has entered it.

I've tried like so:

$(document).on('change','.format-me',function(){
    var value = $(this).val();
    Globalize.culture("en-US");
    console.log(Globalize.format(value));
});

But it is not working, as the logged number looks exactly the same as the one entered by the user. Why isn't Globalize changing the format as needed?

Answer

Jukka K. Korpela picture Jukka K. Korpela · May 27, 2013

The reason why the logged number looks exactly the same as the one entered is that you are calling Globalize.format() with a string argument – it will then simply return its argument, as documented, assuming you are using Globalize.js (originally called jQuery Globalize, later made independent of jQuery). The value of an input control in HTML is taken as a string, and to be processed as a number, it needs to be converted, somehow.

In this context, it should be parsed with Globalize.parseFloat(), and when logging it, you need to pass e.g. the format parameter n2 (since for a number, the default format is i, which is seldom useful – one of the pitfalls of Globalize.js):

$(document).on('change','.format-me',function(){
    var value = $(this).val();
    Globalize.culture("en-US");
    var num = Globalize.parseFloat(value);
    if(isNaN(num)) console.log('Parsing failed');
    console.log(Globalize.format(num, "n2"));
});

However, I do not quite see the point in logging the number in a localized format. The user enters a number in a localized format, but for any processing (client-side or server-side), it should be stored in an internationalized format. A localized format may then later be used when displaying some results to the user.