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(n um, 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(integ er) - 1, 0, -1):
count += 1
formatted.appen d(integer[i])
if count % 3 == 0:
formatted.appen d(",")
integer = "".join(formatt ed[::-1])
return integer+decimal 5 14711
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(n um, 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(integ er) - 1, 0, -1):
count += 1
formatted.appen d(integer[i])
if count % 3 == 0:
formatted.appen d(",")
formatted.appen d(integer[0]) # this misses in your part
integer = "".join(formatt ed[::-1])
return integer+decimal
#
# add something like this: it helps to prevent you break your code
#
import unittest
class test_number_for mat(unittest.Te stCase):
def test(self):
self.assertEqua l(number_format (1000000, 2), '1,000,000.00')
self.assertEqua l(number_format (100000, 2), '100,000.00')
self.assertEqua l(number_format (100, 2), '100.00')
self.assertEqua l(number_format (1000000.33, 2), '1,000,000.33')
self.assertEqua l(number_format (1000000.333, 2), '1,000,000.33')
self.assertEqua l(number_format (1000000.3, 2), '1,000,000.30')
self.assertEqua l(number_format (123456, 2), '123,456.00')
self.assertEqua l(number_format (12345, 2), '12,345.00')
self.assertEqua l(number_format (123, 2), '123.00')
self.assertEqua l(number_format (123456.33, 2), '123,456.33')
self.assertEqua l(number_format (12345.333, 2), '12,345.33')
self.assertEqua l(number_format (123.3, 2), '123.30')
suite = unittest.makeSu ite(test_number _format)
unittest.TextTe stRunner(verbos ity=2).run(suit e)
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(n um, places=0)
"""Format a number according to locality and given places"""
locale.setlocal e(locale.LC_ALL , locale.getdefau ltlocale()[0])
return locale.format(" %.*f", (places, num), 1) wi******@hotmai l.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(n um, 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(integ er) - 1, 0, -1): count += 1 formatted.appen d(integer[i]) if count % 3 == 0: formatted.appen d(",") formatted.appen d(integer[0]) # this misses in your part integer = "".join(formatt ed[::-1]) return integer+decimal
# # add something like this: it helps to prevent you break your code # import unittest
class test_number_for mat(unittest.Te stCase): def test(self): self.assertEqua l(number_format (1000000, 2), '1,000,000.00') self.assertEqua l(number_format (100000, 2), '100,000.00') self.assertEqua l(number_format (100, 2), '100.00') self.assertEqua l(number_format (1000000.33, 2), '1,000,000.33') self.assertEqua l(number_format (1000000.333, 2), '1,000,000.33') self.assertEqua l(number_format (1000000.3, 2), '1,000,000.30') self.assertEqua l(number_format (123456, 2), '123,456.00') self.assertEqua l(number_format (12345, 2), '12,345.00') self.assertEqua l(number_format (123, 2), '123.00') self.assertEqua l(number_format (123456.33, 2), '123,456.33') self.assertEqua l(number_format (12345.333, 2), '12,345.33') self.assertEqua l(number_format (123.3, 2), '123.30')
suite = unittest.makeSu ite(test_number _format) unittest.TextTe stRunner(verbos ity=2).run(suit e)
This is a little faster:
def number_format(n um, places=0):
"""Format a number according to locality and given places"""
locale.setlocal e(locale.LC_ALL , "")
return locale.format(" %.*f", (places, num), True)
I tested this ok with my test
"wi******@hotma il.com" <ma**********@g mail.com> wrote in
news:11******** **************@ f14g2000cwb.goo glegroups.com: def number_format(n um, places=0): """Format a number according to locality and given places""" locale.setlocal e(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.4450000 0, 2 )
2,312,753.44 print number_format( 2312753.4450000 1, 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
Rick Zantow <rz*****@gmail. com> wrote: print number_format( 2312753.4450000 0, 2 )2,312,753.44 print number_format( 2312753.4450000 1, 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.4450000 0
2312753.4449999 998 2312753.4450000 1
2312753.4450000 101
So, yeah, the nature of floating points is going to make that
first one round "unexpected ly".
--
\S -- si***@chiark.gr eenend.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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 that can be entered by users,
these expressions are defined by another app so i can't change the
format of the expressions. I've managed to support the...
|
by: Douglas |
last post by:
Gday,
How would I format a number so that:
TheValue = 32500
Displays in the TextBox as: $32,500.00
|
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
attached), yet when I ran it for 28/09/2003 (UK date format) it
returned Week 39. I would have expected it to return Week 40.
However, I'm really stuck...
|
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 that there are different start days of the week so I would
presume any function would provide that facility. Hope you can help
Mark
|
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 example is: 36,525 represents 01/01/1900. The starting point date is considered to be :
00/00/0000. I have looked thru Help and used Google and...
| |
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 7 digits in base 10.
Is there a way to compute that information without actually evaluating
the factorial?
|
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
|
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 places. The function accepts a compulsory first argument of type double (the number to be formatted) and a second optional argument of type integer...
|
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 8.0000000000000002E-2. This causes the xslt function format-number() to fail.
I use it as
<xsl:value-of select='format-number(8.0000000000000002E-2, "###,###.00")' />...
|
by: FAQ server |
last post by:
-----------------------------------------------------------------------
FAQ Topic - How do I format a Number as a String with
exactly 2 decimal places?
-----------------------------------------------------------------------
When formatting money for example, to format 6.57634 to
6.58, 6.5 to 6.50, and 6 to 6.00?
Rounding of x.xx5 is...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |