473,408 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Number Format function

I'm am relatively new to Python but use it daily. Today, I went looking
for a function, like PHP's number_function, that will take a number and
return a string with number formatted with grouped thousands and the
decimal portion rounded to a given number of places. This is certainly
needed when you want to take a floating-point value from a database and
display it as currency, for instance. I could not find what I was
looking for so I wrote the following function. I hope either (a) I've
provided something useful or (b) someone can tell me what I *should*
have done! Thanks.

import math

def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""

#is_negative = (num < 0)
#if is_negative:
# num = -num

places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""

count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer[i])
if count % 3 == 0:
formatted.append(",")

integer = "".join(formatted[::-1])
return integer+decimal

Feb 8 '06 #1
5 14702
Your code has a little bug, I highly recommend to add a test to your
code, for an idea see below - I fixed your code as well.

#!/usr/bin/env python
import math

def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal
places"""
#is_negative = (num < 0)
#if is_negative:
# num = -num

places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""

count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer[i])
if count % 3 == 0:
formatted.append(",")
formatted.append(integer[0]) # this misses in your part
integer = "".join(formatted[::-1])
return integer+decimal
#
# add something like this: it helps to prevent you break your code
#
import unittest

class test_number_format(unittest.TestCase):
def test(self):
self.assertEqual(number_format(1000000, 2), '1,000,000.00')
self.assertEqual(number_format(100000, 2), '100,000.00')
self.assertEqual(number_format(100, 2), '100.00')
self.assertEqual(number_format(1000000.33, 2), '1,000,000.33')
self.assertEqual(number_format(1000000.333, 2), '1,000,000.33')
self.assertEqual(number_format(1000000.3, 2), '1,000,000.30')
self.assertEqual(number_format(123456, 2), '123,456.00')
self.assertEqual(number_format(12345, 2), '12,345.00')
self.assertEqual(number_format(123, 2), '123.00')
self.assertEqual(number_format(123456.33, 2), '123,456.33')
self.assertEqual(number_format(12345.333, 2), '12,345.33')
self.assertEqual(number_format(123.3, 2), '123.30')

suite = unittest.makeSuite(test_number_format)
unittest.TextTestRunner(verbosity=2).run(suite)

Feb 8 '06 #2
Thanks. I noticed the bugs later. But after talking with my boss, he
suggested something more elegant (again *untested*, yet):

import locale

def number_format(num, places=0)
"""Format a number according to locality and given places"""
locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()[0])
return locale.format("%.*f", (places, num), 1)

wi******@hotmail.com wrote:
Your code has a little bug, I highly recommend to add a test to your
code, for an idea see below - I fixed your code as well.

#!/usr/bin/env python
import math

def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal
places"""
#is_negative = (num < 0)
#if is_negative:
# num = -num

places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""

count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer[i])
if count % 3 == 0:
formatted.append(",")
formatted.append(integer[0]) # this misses in your part
integer = "".join(formatted[::-1])
return integer+decimal
#
# add something like this: it helps to prevent you break your code
#
import unittest

class test_number_format(unittest.TestCase):
def test(self):
self.assertEqual(number_format(1000000, 2), '1,000,000.00')
self.assertEqual(number_format(100000, 2), '100,000.00')
self.assertEqual(number_format(100, 2), '100.00')
self.assertEqual(number_format(1000000.33, 2), '1,000,000.33')
self.assertEqual(number_format(1000000.333, 2), '1,000,000.33')
self.assertEqual(number_format(1000000.3, 2), '1,000,000.30')
self.assertEqual(number_format(123456, 2), '123,456.00')
self.assertEqual(number_format(12345, 2), '12,345.00')
self.assertEqual(number_format(123, 2), '123.00')
self.assertEqual(number_format(123456.33, 2), '123,456.33')
self.assertEqual(number_format(12345.333, 2), '12,345.33')
self.assertEqual(number_format(123.3, 2), '123.30')

suite = unittest.makeSuite(test_number_format)
unittest.TextTestRunner(verbosity=2).run(suite)


Feb 8 '06 #3
This is a little faster:

def number_format(num, places=0):
"""Format a number according to locality and given places"""
locale.setlocale(locale.LC_ALL, "")
return locale.format("%.*f", (places, num), True)

I tested this ok with my test

Feb 8 '06 #4
"wi******@hotmail.com" <ma**********@gmail.com> wrote in
news:11**********************@f14g2000cwb.googlegr oups.com:
def number_format(num, places=0):
"""Format a number according to locality and given places"""
locale.setlocale(locale.LC_ALL, "")
return locale.format("%.*f", (places, num), True)


There are some edge cases in the format conversion that could present
some issues. For example:
print number_format( 2312753.44500000, 2 ) 2,312,753.44 print number_format( 2312753.44500001, 2 )

2,312,753.45

I would expect the first to produce the same results as the second, but,
I suppose because of one of floating point's features, it doesn't work
that way.

--
rzed
Feb 8 '06 #5
Rick Zantow <rz*****@gmail.com> wrote:
print number_format( 2312753.44500000, 2 )2,312,753.44 print number_format( 2312753.44500001, 2 )2,312,753.45

I would expect the first to produce the same results as the second, but,
I suppose because of one of floating point's features, it doesn't work
that way.

2312753.44500000 2312753.4449999998 2312753.44500001

2312753.4450000101

So, yeah, the nature of floating points is going to make that
first one round "unexpectedly".

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Feb 9 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: netclectic | last post by:
Hi folks, i've searched and searched and can't find any example of what i'm trying to do. Essentially (i think) i need to add a new operator to Number. I'm using eval to evaluate expressions...
16
by: Douglas | last post by:
Gday, How would I format a number so that: TheValue = 32500 Displays in the TextBox as: $32,500.00
7
by: Shuffs | last post by:
Could someone, anyone please tell me what I need to amend, to get this function to take Sunday as the first day of the week? I amended the Weekday parts to vbSunday (in my code, not the code...
4
by: Mark | last post by:
Hi I have been trying to convert the week number to a range of dates that I can use. It should be fairly simple for you guru's out there but for us mere mortals it is beyond our grasp. I know...
29
by: james | last post by:
I have a problem that at first glance seems not that hard to figure out. But, so far, the answer has escaped me. I have an old database file that has the date(s) stored in it as number of days. An...
109
by: jmcgill | last post by:
Hello. Is there a method for computing the number of digits, in a given numeric base, of N factorial, without actually computing the factorial? For example, 8! has 5 digits in base 10; 10! has...
6
by: JFB | last post by:
Hi all, How can I format a fax number as 888-333-444? The number is coming from database as 8883334444 <ItemTemplate> <%#container.dataItem("cfax")%> </ItemTemplate> Tks JFB
17
by: scan87 | last post by:
Can somone please, please give me the solution for the following problem. I need to submit it on Monday. Write a global function called format, which formats numbers with a given number of decimal...
3
ashsa
by: ashsa | last post by:
Hi everyone, I am trying to display a numeric value fetched from an sql server table which is stored in the exponential notation. For eg, 0.08 is getting stored in the table as...
4
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I format a Number as a String with exactly 2 decimal places?...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.