Question

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?

Was it helpful?

Solution 2

I've just realized that using the jquery spinner, there's a very simple way to do what I was trying:

$(document).on('change','.check-float',function(){
    var value = $(this).val();
    $(this).spinner( "value", value );
});

When you assign a value to the spinner like so, it automatically format the value accordingly to the culture assigned to the spinner!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top