Internationalization(Number formatting "num.toLocaleString()") not working for chrome - javascript

i want do number formatting in Javascript.. and i use the following method
num.toLocaleString() which will work for Firefox, IE but doesnt work for Google Chrome..
Wat i need to add for it work in chrome browser.

The toLocaleString() method is by definition implementation-dependent: it uses the implementation locale, such as browser locale. So if I were looking at your page that uses the method, I would see numbers formatted according to Finnish or English locale, depending on which browser I’m using.
What you want is localization by the locale of the page, and for this you need something else. In simple cases you might code it yourself, but number formatting is in general complicated, making it reasonable to use a library, such as Globalize. Check out the compact source of a simple demo. In Globalize, you use standard language codes when specifying the locale.

Internationalization is always challenging and unfortunately there doesn't seem to be a consistent/pervasive solution to it. Your best bet is to use a 3rd party library to take care of things for you.
We rely heavily on googles closure library, which has some pretty powerful i18n (internationalization) tools. Take a look at http://www.daveoncode.com/2009/11/26/goog-i18n-numberformat-formatting-number-locale-string/ for an example of how to use it. In the end, it becomes as easy as:
// define italian number format symbols
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it_IT;
// create new decimal formatter (PERCENT, CURRENCY, SCIENTIFIC are options)
formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.DECIMAL);
// view formatted and localized string
alert(formatter.format(15650.579));
If you are new to closure, don't worry. It's not hard to get set up and has a multitude of excellent helper classes that you may find useful.
http://code.google.com/closure/library/docs/gettingstarted.html

The JavaScript internationalization support is quite poor (as you have discovered).
You might take a look at https://github.com/jquery/globalize
It handles number formatting, and also dates, times, currencies.

A bit of voodoo can implement your own number formatting. You could build this into String.prototype, but I didnt want that, since its localized.
function reverse(str) {
return str.split('').reverse().join('');
}
function num2str(num) {
var str = num+"";
// european
// return reverse(reverse(str.replace('.',',')).replace(/\d{3}/g,'$&.').replace(/\.$/,''));
// american
return reverse(reverse(str).replace(/\d{3}/g,'$&,').replace(/\,$/,''));
}
and then its
> console.log(25000.45)
> 25,000.45

Related

when to, or to not, use toLocale methods?

TLDR below
I was reading through the Standard Built-In Objects portion of JavaScript on MDN and noticed that there are these methods that utilize 'Locale' and are used specifically, from what I can gather, to format return text from the method in a locally defined format if it exists. Apparently it causes an issue with Turkey(I don't know if there are others)
As far as I could tell, from what I've looked into, these were all implemented in ES 5.1 circa 2011. In fact, in one of the SO links in the references below it's actively pointed out that a reason why Angular 1.x might be using toString instead of toLocaleString is because of backwards compatibility with browsers that didn't yet completely adopt ES5.1 - simple aside: I don't know if that's exactly the case but it seems reasonable.
so I looked up the ES6 spec to check out the method:
On Object:
15.2.4.3 Object.prototype.toLocaleString ( ) This function returns the result of calling toString(). NOTE This function is provided to
give all Objects a generic toLocaleString interface, even though not
all may use it. Currently, Array, Number, and Date provide their own
locale-sensitive toLocaleString methods. NOTE The first parameter to
this function is likely to be used in a future version of this
standard; it is recommended that implementations do not use this
parameter position for anything else.
On Array:
15.4.4.3 Array.prototype.toLocaleString ( )
The elements of the array are converted to strings using their toLocaleString methods, and these strings are
then concatenated, separated by occurrences of a separator string that has been derived in an implementationdefined
locale-specific way. The result of calling this function is intended to be analogous to the result of
toString, except that the result of this function is intended to be locale-specific.
On String:
15.5.4.17 String.prototype.toLocaleLowerCase ( )
This function works exactly the same as toLowerCase except that its result is intended to yield the correct result
for the host environment’s current locale, rather than a locale-independent result. There will only be a difference in
the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.
NOTE The toLocaleLowerCase function is intentionally generic; it does not require that its this value be a String object.
Therefore, it can be transferred to other kinds of objects for use as a method.
NOTE The first parameter to this function is likely to be used in a future version of this standard; it is recommended that
implementations do not use this parameter position for anything else.
The original ToLowerCase for Clarity:
15.5.4.16 String.prototype.toLowerCase ( )
If this object is not already a string, it is converted to a string. The characters in that string are converted one by one
to lower case. The result is a string value, not a String object.
The characters are converted one by one. The result of each conversion is the original character, unless that
character has a Unicode lowercase equivalent, in which case the lowercase equivalent is used instead.
NOTE The result should be derived according to the case mappings in the Unicode character database (this explicitly includes
not only the UnicodeData.txt file, but also the SpecialCasings.txt file that accompanies it in Unicode 2.1.8 and later).
NOTE The toLowerCase function is intentionally generic; it does not require that its this value be a String object. Therefore, it
can be transferred to other kinds of objects for use as a method
(toLocaleUpperCase/toUpperCase reads exactly the same)
Given all that, and with the release of ES6 and it being largely adopted I am confused. I feel that toLowerCase and toUpperCase are used pretty commonly for validation purposes(though less so with ES6) and changing them to utilize Locale seems wrong because you would be checking against unknown formatting. So Okay, not really useful for validation. So what about outputting to the DOM with toLocaleString? It seems plausible, but again, you're dealing with unknowns. Say your locale isn't formatted and you wanted the integer 1000 to be displayed as '1,000'. (I've read that this happens with en-GB) It will leave it out of your hands and you may never even know that it's not displaying as you wanted it to.
TLDR:
Is there a practical use case for methods like toLocaleString toLocaleLowerCase toLocaleUpperCase, etc.? Should they be largely ignored?
Note: I realize this is on the line of opinionated, but I don't think it is. I'm looking for rational cases in which these may be applicable if they exist. e.g. like asking 'what you would use .call for' as opposed to 'do you think .call is better than .apply'
References
MDN String Prototype: toLocaleLowerCase
SO: Difference Between toLocaleLowerCase and toLowerCase?
SO: In which exactly js engines are toLowerCase toUpperCase locale sensitive?
SO: JavaScript difference between toString and toLocaleString methods of date?
It seems plausible, but again, you're dealing with unknowns.
Yes. You need to get to know them.
It will leave it out of your hands and you may never even know that it's not displaying as you wanted it to.
Indeed. If you want/need to have full control over your output, you need to implement the formatting yourself. If you only say, hey, it's a number, please format it to whatever you think is best for a British locale, then you can use it.
Is there a practical use case for methods like toLocaleString etc.?
Yes! You will want to use them in an environment that supports the ECMA-402 Standard.
From the API Overview:
"The ECMAScript 2016 Internationalization API Specification provides several key pieces of language-sensitive functionality that are required in most applications: String comparison (collation), number formatting, date and time formatting, and case conversion. While the ECMAScript 2016 Language Specification provides functions for this basic functionality (on Array.prototype: toLocaleString; on String.prototype: localeCompare, toLocaleLowerCase, toLocaleUpperCase; on Number.prototype: toLocaleString; on Date.prototype: toLocaleString, toLocaleDateString, and toLocaleTimeString), it leaves the actual behaviour of these functions largely up to implementations to define. The ECMAScript 2016 Internationalization API Specification provides additional functionality, control over the language and over details of the behaviour to be used, and a more complete specification of required functionality."
Should they be largely ignored?
In an unknown environment, probably. But not when you know what they do (because you control the environment, or you expect it to conform to ECMA-402), because in those cases they can be very useful and take a great deal of work off you.

Change Date Format from millisecond

I have millisecond and i want to convert it in format Feb-01-2014 09:12:12. I have used following code
var today = new Date(1419359400000);
var p=today.toLocaleFormat('%b-%d-%Y %H:%M:%S');
But it is not working in chrome
Thanks
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat reads:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Use some date library if you find yourself needing to formats a lot or use the native functions today.getYear(), today.getMonth() etc.
Keep in mind that toLocaleFormat uses the operating system locale which might not actually be what you want. Your dates might appear in a different language than the rest of your application.

JavaScript library for formatting AND parsing Date and Numbers

I'm looking for a JavaScript library which can parse and format date values and numbers. It should not be too big or complicated just 4 methods would suffice for me: parseDate, formatDate, parseNumber, formatNumber
//dt is a JavaScript date object, str a string containing a date, formatoptions specifies the format
var dt = parseDate(str, formatoptions);
var str = formatDate(dt, formatoptions);
//same applies for parseNumber and formatNumber just replace dt with nr which represents a JavaScript number
I've already asked Mr. Google but there are sooo many libraries and articles out there that it is hard to find something good. Many libs can format a number or date but can't parse them. Or they are not stable (reasonably bug-free).
Any recommendations?
update:
Sadly serverside processing is not really on option. I know support for date and time manipulation is much better in PHP or ASP
I included some sample code what I would expect from the parse and format functions
update 2:
I found quite a good library for formatting numbers which is called jquery-numberformatter
I have been using date.js from http://www.datejs.com. The parser in the home page will give you an idea of its capabilities.
These days I would look at MomentJs. Theres plenty of documentation and tests.

jQuery datetime formatter

Is there a working jQuery plugin (or a javascript 'library') for formatting datetimes? I found some, but they were:
not working with hours and minutes (the one from datapicker)
not fully functional - can't give you names of months, leading zeroes, etc.
are just a piece of code written in some blog.
Of course I can implement it, but it'd be better to reuse one. I seek functionality similar to Java's SimpleDateFormat
I've written a JavaScript implementation of the format() method of Java's SimpleDateFormat: http://www.timdown.co.uk/code/simpledateformat.php
The code is a few years old and I'd do it a bit differently now, but it's well tested and works.
Did you try date.js ?
It has a pattern recognition to format dates that is easy to use and has plenty of localisation files available.
ie: Date.today().toString("d-MMM-yyyy HH:mm")
I use http://blog.stevenlevithan.com/archives/date-time-format
Not sure whether it fits all your requirements, but this looks good one:
jquery-dateFormat

Is metaprogramming possible in Javascript?

During my routine work, i happened to write the chained javascript function which is something like LINQ expression to query the JSON result.
var Result = from(obj1).as("x").where("x.id=5").groupby("x.status").having(count("x.status") > 5).select("x.status");
It works perfectly and give the expected result.
I was wondering this looks awesome if the code is written like this (in a more readable way)
var Result = from obj1 as x where x.status
groupby x.status having count(x.status) > 5
select x.status;
is there a way to achieve this??
Cheers
Ramesh Vel
No. JavaScript doesn't support this.
But this looks quite good too:
var Result = from(obj1)
.as("x")
.where("x.id=5")
.groupby("x.status")
.having(count("x.status") > 5)
.select("x.status");
Most people insist on trying to metaprogram from inside their favorite language. That doesn't work if the language doesn't support metaprogramming well; other answers have observed that JavaScript does not.
A way around this is to do metaprogramming from outside the language, using
program transformation tools. Such tools can parse source code, and carry out arbitrary transformations on it (that's what metaprogramming does anyway) and then spit the revised program.
If you have a general purpose program transformation system, that can parse arbitrary languages, you can then do metaprogramming on/with whatever language you like. See our DMS Software Reengineering Toolkit for such a tool, that has robust front ends for C, C++, Java, C#, COBOL, PHP, and ECMAScript and a number of other programming langauges, and has been used for metaprogramming on all of these.
In your case, you want to extend the JavaScript grammar with new syntax for SQL queries, and then transform them to plain JavaScript. (This is a lot like Intentional Programming)
DMS will easily let you build a JavaScript dialect with additional rules, and then you can use its program transformation capabilities to produce the equivalent standard Javascript.
Having said, that, I'm not a great fan of "custom syntax for every programmer on the planet" which is where Intentional Programming leads IMHO.
This is a good thing to do if there is a large community of users that would find this valuable. This idea may or may not be one of them; part of the problem is you don't get to find out without doing the experiment, and it might fail to gain enough social traction to matter.
although not quite what you wanted, it is possible to write parsers in javascript, and just parse the query (stored as strings) and then execute it. e.g.,using libraries like http://jscc.jmksf.com/ (no doubt there are others out there) it shouldnt be too hard to implement.
but what you have in the question looks great already, i m not sure why you'd want it to look the way you suggested.
Considering that this question is asked some years ago, I will try to add more to it based on the current technologies.
As of ECMAScript 6, metaprogramming is now supported in a sense via Symbol, Reflect and Proxy objects.
By searching on the web, I found a series of very interesting articles on the subject, written by Keith Kirkel:
Metaprogramming in ES6: Symbols and why they're awesome
In short, Symbols are new primitives that can be added inside an object (without practically being properties) and are very handy for passing metaprogramming properties to it among others. Symbols are all about changing the behavior of existing classes by modifying them (Reflection within implementation).
Metaprogramming in ES6: Part 2 - Reflect
In short, Reflect is effectively a collection of all of those “internal methods” that were available exclusively through the JavaScript engine internals, now exposed in one single, handy object. Its usage is analogous to the Reflection capabilities of Java and C#. They are used to discover very low level information about your code (Reflection through introspection).
Metaprogramming in ES6: Part 3 - Proxies
In short, Proxies are handler objects, responsible for wrapping objects and intercepting their behaviors through traps (Reflection through intercession).
Of course, these objects provide specific metaprogramming capabilities, much more restrictive compared to metaprogramming languages, but still can provide handy ways of basic metaprogramming, mainly through Reflection practices, in fact.
In the end, it is worth mentioning that there is some worth-noticing ongoing research work on staged metaprogramming in JavaScript.
Well, in your code sample:
var Result = from(obj1)
.as("x")
.where("x.id=5")
.groupby("x.status")
.having(count("x.status") > 5)
.select("x.status");
The only problem I see (other than select used as an identifier) is that you embed a predicate as a function argument. You'd have to make it a function instead:
.having(function(x){ return x.status > 5; })
JavaScript has closures and dynamic typing, so you can do some really nifty and elegant things in it. Just letting you know.
In pure JS no you can not. But with right preprocessor it is possible.
You can do something similar with sweet.js macros or (God forgive me) GPP.
Wat you want is to change the javascript parser into an SQL parser. It wasn't created to do that, the javascript syntax doesn't allow you to.
What you have is 90% like SQL (it maps straight onto it), and a 100% valid javascript, which is a great achievement. My answer to the question in the title is: YES, metaprogramming is possible, but NO it won't give you an SQL parser, since it's bound to use javascript grammar.
Maybe you want something like JSONPath if you've got JSON data. I found this at http://www.json.org/. Lots of other tools linked to from there if it's not exactly what you need.
(this is being worked on as well: http://docs.dojocampus.org/dojox/json/query)

Categories