I came across this problem while building an app recently and thought it might be interesting to share. The problem we are trying to solve is of displaying numbers according to locale. Eg. in india, number 100000 is written as 1,00,000 while in US it is written as 100,000. So, how can we write a program to format numbers properly according to the locale in Javascript and Python is the question we are trying to answer.
The raw or brute force way for doing this is to write a program from scratch. However, to be able to handle different locales we will have to come up with a pretty non-trivial program. Since I was concentrating on Indian locale (100000 as 1,00,000 etc.), I came up with a simple program for doing the same in Javascript.
|
|
The logic here is pretty straightforward. If the number of digits is even then we append the first digit followed by a comma and append comma every third digit. Else, we just append comma every third digit. Of course, there are lots of other ways to do the same. However, the preferred way is to just use the builtin internationalization module (Intl) in JS.
|
|
We can customize the output even more by passing in options argument and also locales. Since I was mainly interested in Indian locale I ve used “en-IN”. For more information please read Intl MDN docs Python too has a module called locale.
|
|
As you can see both python and javascript have quite good support for internationalization.
Improve programming skills through live coding solution for programming puzzles and application …
View DetailsGo programming language is amongst the most popular languages these days. The only language with …
View DetailsGain deep understanding of programming and computer working through this beginner C Programming …
View Details