JavaScript has a number formatter (part of the Internationalization API).
// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
// These options are needed to round to whole numbers if that's what you want.
//minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
//maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});
formatter.format(2500); /* $2,500.00 */
Use undefined
in place of the first argument ('en-US'
in the example) to use the system locale (the user locale in case the code is running in a browser). Further explanation of the locale code.
Here's a list of the currency codes.
Intl.NumberFormat vs Number.prototype.toLocaleString
A final note comparing this to the older .toLocaleString
. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) does not actually support locales: it uses the system locale. So when debugging old browsers, be sure that you're using the correct version (MDN suggests to check for the existence of Intl
). There isn't any need to worry about this at all if you don't care about old browsers or just use the shim.
Also, the performance of both is the same for a single item, but if you have a lot of numbers to format, using Intl.NumberFormat
is ~70 times faster. Therefore, it's usually best to use Intl.NumberFormat
and instantiate only once per page load. Anyway, here's the equivalent usage of toLocaleString
:
(2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
}); /* $2,500.00 */
Some notes on browser support and Node.js
- Browser support is no longer an issue nowadays with 98% support globally, 99% in the US and 99+% in the EU
- There is a shim to support it on fossilized browsers (like Internet Explorer 8), should you really need to
- Node.js before v13 only supports
en-US
out of the box. One solution is to install full-icu, see here for more information
- Have a look at CanIUse for more information
The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print
can be get using the str()
function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you '2008-11-22 19:53:42'
.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr()
function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'
.
What happened is that when you have printed the date using print
, it used str()
so you could see a nice date string. But when you have printed mylist
, you have printed a list of objects and Python tried to represent the set of data, using repr()
.
The How: what do you want to do with that?
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str()
. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date)
.
One last thing. When you tried to print the dates, you printed mylist
. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str()
because print will use it for you. But it should not become a habit :-)
Practical case, using your code
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Advanced date formatting
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime()
method.
strftime()
expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%"
represent a format for something:
%d
is the day number (2 digits, prefixed with leading zero's if necessary)
%m
is the month number (2 digits, prefixed with leading zero's if necessary)
%b
is the month abbreviation (3 letters)
%B
is the month name in full (letters)
%y
is the year number abbreviated (last 2 digits)
%Y
is the year number full (4 digits)
etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in
strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Localization
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
Best Answer
That's simple, add the altFormats config option: