473,395 Members | 1,442 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,395 software developers and data experts.

How to truncate/round-off decimal numbers?

Hi,

I want to truncate every number to 2 digits after the decimal point. I
tried the following but it doesnt work.
a = 2
b = 3
round(a*1.0 / b,2)

0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.
Jun 20 '06 #1
13 42847
MTD
> >>> a = 2
b = 3
round(a*1.0 / b,2) 0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.


This is because of floating point inaccuracy. The system cannot
accurately represent some integers, however it does its best to
approximate them. Notice this:
x = 2.0/3
x 0.66666666666666663 round(x,2) 0.67000000000000004 s = str(round(x,2))
s

'0.67'

Jun 20 '06 #2
MTD
> The system cannot
accurately represent some integers,


Er, I meant FLOATS. Doh.

Anyway, just to underline the example:
x 0.66666666666666663 s = str(round(x,2))
s '0.67' f = float(s)
f 0.67000000000000004 f == round(x,2)

True

Jun 20 '06 #3
Girish Sahani a écrit :
Hi,

I want to truncate every number to 2 digits after the decimal point. I
tried the following but it doesnt work.
a = 2
b = 3
round(a*1.0 / b,2) 0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.


There are two operations:

1) calculate of round(), which return a float number result, with the
well known problem of floating point numbers represantation (see the FAQ).

2) print that number, where default printing of last expression result
in the cli interpreter displays up to the highest precision, print
statement works differently:
a=2
b=3
c=round(a*1.0/b,2)
c 0.67000000000000004 print c 0.67


A+

Laurent.
Jun 20 '06 #4
Sybren Stuvel wrote:
Girish Sahani enlightened us with:
I want to truncate every number to 2 digits after the decimal point....
> a = 2
> b = 3
> round(a*1.0 / b,2)

0.67000000000000004


If you want to format it, use '%.2f' % (float(a)/b)


Sybren has this right. If you follow everyone else's advice,
you'll eventually discover:
print round(11024. / 5000.1, 2)

only gives you "2.2", not "2.20" (which is what, I suspect, you want).

--Scott David Daniels
sc***********@acm.org
Jun 20 '06 #5
MTD wrote:
The system cannot
accurately represent some integers,


Er, I meant FLOATS. Doh.


You were also right the first time. But it only applies to integers
with more than 53 bits.

Jun 20 '06 #6
In article <ma***************************************@python. org>,
Girish Sahani <gi****@cse.iitb.ac.in> wrote:

I want to truncate every number to 2 digits after the decimal point. I
tried the following but it doesnt work.
a = 2
b = 3
round(a*1.0 / b,2)

0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.


You should also consider switching to the decimal module if you care
about getting correct results.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"I saw `cout' being shifted "Hello world" times to the left and stopped
right there." --Steve Gonedes
Jun 20 '06 #7
Hi,

just a thought: if you *always* work with "floats" with two decimals,
you are in fact working with integers, but you represent them as a
floats - confusing for the internal representation.

So why not work with int(float * 100) instead? This way you only have
to take care of roundoffs etc when dividing.

"int (+|-|*) int" = int
"int / int" = int / int + int % int

Integers are nice, me like integers.

/per9000

Jun 21 '06 #8
oops, should be something like this:

"int / int" = "int / int, int % int"

/per9000

Jun 21 '06 #9
> just a thought: if you *always* work with "floats" with two decimals,
you are in fact working with integers, but you represent them as a
floats - confusing for the internal representation.

So why not work with int(float * 100) instead? This way you only have
to take care of roundoffs etc when dividing.

And why won't you work with decimal module ?
Jun 21 '06 #10

In article <11**********************@g10g2000cwb.googlegroups .com>,
"per9000" <pe*****@gmail.com> writes:
|>
|> just a thought: if you *always* work with "floats" with two decimals,
|> you are in fact working with integers, but you represent them as a
|> floats - confusing for the internal representation.

No, you aren't - you are working with fixed-point, which is something
that is neither integers nor floating-point, but is somewhere in
between. I am (just) old enough to remember when it was used for
numeric work, and to have used it for that myself, but not old enough
to have done any numeric work using fixed-point hardware.

|> So why not work with int(float * 100) instead? This way you only have
|> to take care of roundoffs etc when dividing.

And multiplying, and calling most mathematical functions.
Regards,
Nick Maclaren.
Jun 21 '06 #11
Nick Maclaren wrote:
|> just a thought: if you *always* work with "floats" with two decimals,
|> you are in fact working with integers, but you represent them as a
|> floats - confusing for the internal representation.

No, you aren't - you are working with fixed-point
Nick, your answer has so many layers, I'll try to explain how I think
:-D

1) if you use integers you can think of them as having one part bigger
than 100 and one part smaller than 100, like so:
a = 11122
(a/100,a%100) (111, 22)
Here the output 111,22 looks like something else than an integer, but
this is just a matter of representation. a *is* an integer, but we
represent it *as if it was* a "decimal" number. (Compare with
(minutes,seconds) or (euro,cents) or (feet,inch) or any other
"arbitrary" position system)

2) If we use floats with two decimals b = 222.33
b 222.33000000000001
they look like fix-point numbers (I had to look it up
http://en.wikipedia.org/wiki/Fixed-point :-D) but python stores it
(correct me if I am wrong) as a float (or double or quad or whatever).
If we want to work with fix-point aritmetics we have to invent new
functions to do most math.

3) Most "decimal numbers" cannot be stored exactly as floats - that is
why b gave the ugly print. But some can, f.x quart = 0.25
quart 0.25
quart translates to a finite "decimal" number in binary (0.01 I think).

The point is: representing should-be integers as floats makes you loose
precision (negligable probalby but still...).

4) |> So why not work with int(float * 100) instead? This way you only have
|> to take care of roundoffs etc when dividing.

And multiplying, and calling most mathematical functions.

You are correct of course. My mistake.

But, the multiplication is exact before you start rounding off - I wont
start counting ordos for int*int vs. float*float, but it could have
some advantages a 11122 b 22233 a*b 247275426 (a*b/10000,a*b%10000)

(24727, 5426)
On the other hand you will quickly loose accuracy if you perform
multiple multiplications or divisions or use other mathematical
functions.

5) So, when could this way of thinking be useful? Well, rarely, but if
you only add/subtract "decimals" and/or multiply "decimals" with whole
numbers or if you want to use some non-metric system to do scientific
stuff (compute square feet when having (feet1,inch1) * (feet2,inch2)
assuming that inches are atomic.)

This could of course be extended to
(feet, inch, quarter_of_afoot, sixteeth_of_a_foot) if you'd like - it
is all a matter of representation.

Regards,
Per
----
"It is a gift. A gift to the foes of 'the Terrorists'. Why not
use this 'terrorism'? Long has my father, 'George Bush Sr',
kept the forces of 'the terrorists' at bay. By the blood of
our people are your lands kept safe. Give 'the land of the
brave' the weapon of the enemy. Let us use it against him."

Jun 21 '06 #12
Nick Maclaren wrote: (of fixed point)
.... I am (just) old enough to remember when it was used for
numeric work, and to have used it for that myself, but not old enough
to have done any numeric work using fixed-point hardware.


You are using fixed point hardware today. Fixed point tracked the
"decimal point" (or "binary point" or whatever) in the mind of the
programmer, not in the state of the hardware. There never was
"fixed point hardware," it was simply a way of viewing the results
of the gates of the same hardware we use today.

--
--Scott David Daniels
sc***********@acm.org
Jun 21 '06 #13

In article <44********@nntp0.pdx.net>,
Scott David Daniels <sc***********@acm.org> writes:
|> Nick Maclaren wrote: (of fixed point)
|> > .... I am (just) old enough to remember when it was used for
|> > numeric work, and to have used it for that myself, but not old enough
|> > to have done any numeric work using fixed-point hardware.
|>
|> You are using fixed point hardware today. Fixed point tracked the
|> "decimal point" (or "binary point" or whatever) in the mind of the
|> programmer, not in the state of the hardware. There never was
|> "fixed point hardware," it was simply a way of viewing the results
|> of the gates of the same hardware we use today.

Er, no. Analogue hardware never was fixed-point, and I have used that :-)

More relevantly, you are using a very parochial and unusual interpretation
of the word 'hardware'. In normal usage, it includes everything below
the instruct set specification (now often called the ABI). And I can
assure you that there is a considerable difference between the hardware
that provides a floating-point interface at the ABI and that which
provides a fixed-point interface.
Regards,
Nick Maclaren.
Jun 21 '06 #14

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

Similar topics

3
by: martin | last post by:
Hi, We have a heavily used production server and a table which logs every hit on a web site. This table has grown large over time and we want to clear it down as efficiently as possible. We would...
3
by: LineVoltageHalogen | last post by:
Greeting All, I have a stored proc that dynamically truncates all the tables in my databases. I use a cursor and some dynamic sql for this: ...... create cursor Loop through sysobjects and...
1
by: New MSSQL DBA | last post by:
I have recently been assigned to take over several MSSQL environments and found some of the existing practice confusing. As most of my previous experiences are on Oracle and Unix platform so would...
1
by: Eddie | last post by:
I have a DataTable.Select() statement with a DateTime field that is being compared to a Date: Dim drCal as DataRow() = tblCal.Select("CalendarItemDate ='12/1/2003'", "CalendarItemDate",...
2
by: rdraider | last post by:
Hi, I am trying to create a script that deletes transaction tables and leaves master data like customer, vendors, inventory items, etc. How can I use TRUNCATE TABLE with an Exists? My problem is...
9
by: Sumanth | last post by:
Are there any implementations of truncate in db2. Is it going to be implemented in the future? Is there an alternate way of doing a truncate of a table that has a high record count without using...
14
by: Sala | last post by:
Hi I want to truncate all data in database ... pls help me how i ll truncate?
10
by: Troels Arvin | last post by:
Hello, Until this date, I believed that DB2 has no TRUNCATE TABLE command. But then I came across...
5
by: Timothy Madden | last post by:
Hello I see there is now why to truncate a file (in C or C++) and that I have to use platform-specific functions for truncating files. Anyone knows why ? I mean C/C++ evolved over many years...
8
by: ananthaisin | last post by:
How to reduce the table size for any table while using truncate or delete statements. In oracle 8i it was truncating the storage space but in 10g it is not .... I have given truncate statement in...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.