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

strings (dollar.cents) into floats

Hi,

i have strings which look like money values (ie 34.45)
is there a way to convert them into float variables?
everytime i try I get this error: "numb = float(my_line) ValueError:
empty string for float()"
"
here's the code

************

import sys
import re

for line in sys.stdin.readlines():
my_line = line.rstrip()
numb = float(my_line)
print numb
Aug 30 '07 #1
16 4099
Ben Finney wrote:
You most likely do *not* want floating-point numbers for currency,
since they rely on the operating system's binary floating point
support which cannot accurately represent decimal fractions.
I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?

/W
Aug 31 '07 #2
Wildemar Wildenburger wrote:
Ben Finney wrote:
>You most likely do *not* want floating-point numbers for currency,
since they rely on the operating system's binary floating point
support which cannot accurately represent decimal fractions.

I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?
There are many, many situations where one is *not* trying to represent numbers
that have nice decimal fractions or the error induced is insignificant to the
problem. For example, I might take temperature readings good to 0.1 degrees
Celcius. I'll type those numbers in decimal even though when I do my
calculations I'll use floating point math because the error (about 1e-15 or so)
is so far below the error in my measurement (about 0.1) that I won't have problems.

Binary floating point has the advantage of being widely implemented and quite
fast compared to decimal floating point.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Aug 31 '07 #3
Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
But what use is there for floats, then? When is it OK to use them?
When one is willing to sacrifice decimal precision for speed of
calculation, and doesn't need the numbers to stay precise. E.g. when
performing millions of calculations on real-world (analogue)
measurements.

--
\ "Too many Indians spoil the golden egg." -- Sir Joh |
`\ Bjelke-Petersen |
_o__) |
Ben Finney
Aug 31 '07 #4
Ben Finney wrote:
Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
>But what use is there for floats, then? When is it OK to use them?

When one is willing to sacrifice decimal precision for speed of
calculation, and doesn't need the numbers to stay precise. E.g. when
performing millions of calculations on real-world (analogue)
measurements.
Traditionally, mainframe computers used BCD arithmetic to handle
currency, and the Decimal module is probably the best way to proceed if
your Python is recent enough to include it.

That isn't to say that currencies can't be handled using floating-point.
The important thing then becomes to round after each calculation rather
than allowing the errors to build up until they become significant
enough to make a difference to the final result.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 31 '07 #5
On 31 Aug, 02:12, Wildemar Wildenburger
<lasses_w...@klapptsowieso.netwrote:
I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?
There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals. There are fractions that
can be exactly represented by decimals that cannot be exactly
represented by floats.

Which one is better? Which do we prefer?

What a float cannot do is to represent a decimal fractional number
(e.g. 1.1) exactly. If we need that, we cannot use floats. A notable
example is monetary computations, it covers 99% of the use for decimal
numbers in computers. For this reason, we should never use floats to
add 10 cents to a dollar. The use of decimals for monetary
calculations is mandatory.

Floats are written as decimal fractional numbers in program code, and
they are printed as decimal fractional numbers on the screen. A novice
programmer may for this reason easily mistake floats for being
decimals. But inside the computer floats are something very different.
Floats do not represent decimal fractional numbers. Floats represent
binary fractional numbers. Decimal numbers are base-10, binary numbers
are base-2. Floats and decimals are similar but different.

It is much easier to manipulate for computers than decimals. Digital
electronics by convention only has two states, TTL voltage levels 0.0
V and 5.0 V, which are taken to mean 0 and 1 in binary (or false and
true in boolean) respectively. Computers work internally with binary
numbers. Floats are preferred to decimals in e.g. numerical maths and
other scientific computing for their better performance speed wise.
Knowledge of the behaviour of floats, e.g. how they cause rounding and
truncation errors, is pivotal in that field of computer science. For
most purposes, we could replace floats with decimals. But then we
would suffer a major speed penalty.

Decimals are only "precise" if the input values can be represented
precisely by decimal fractions. If we typed 1.1 and took that to mean
"one dollar and 10 cents", then certainly "exactly 1.1" was what we
meant. But if we ment "1.1 centigrades read from a mercury
thermometer", we would actually (by convention) mean "something
between 1.05 and 1.14 centigrades". Decimals also fail to be exact if
we try to compute things like "1.0/3.0". 1/3 does not have an exact
representation in decimal, and we get an approximation from the
computer.

For purposes where exact precision is not needed, decimals are neither
better nor worse than floats. This accounts for 99% of the cases where
fractional numbers are used on a computer.

More about floating point numbers here:
http://www.math.byu.edu/~schow/work/...atingPoint.htm
Sturla Molden
Aug 31 '07 #6
sturlamolden wrote:
On 31 Aug, 02:12, Wildemar Wildenburger
<lasses_w...@klapptsowieso.netwrote:
>I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?

There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.
Would you care to give an example?
There are fractions that
can be exactly represented by decimals that cannot be exactly
represented by floats.

Which one is better? Which do we prefer?

What a float cannot do is to represent a decimal fractional number
(e.g. 1.1) exactly. If we need that, we cannot use floats. A notable
example is monetary computations, it covers 99% of the use for decimal
numbers in computers. For this reason, we should never use floats to
add 10 cents to a dollar. The use of decimals for monetary
calculations is mandatory.
That last sentence is patent nonsense, and completely untrue. Many
satisfactory financial applications have been written using only
floating-point arithmetic. Indeed I believe the accountant's Swiss army
knife, the Excel spreadsheet, uses floating-point numbers exclusively.

What you say about floating-point have speed advantages is true, but you
go too far in claiming that decimal arithmetic is mandatory for monetary
calculations. That's about as sensible as saying that base 12 and base
20 arithmetic units were required to calculate in pounds, shillings and
pence.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 31 '07 #7
On 8/31/07, Steve Holden <st***@holdenweb.comwrote:
sturlamolden wrote:
On 31 Aug, 02:12, Wildemar Wildenburger
<lasses_w...@klapptsowieso.netwrote:
I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?
There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.

Would you care to give an example?
There are fractions that
can be exactly represented by decimals that cannot be exactly
represented by floats.

Which one is better? Which do we prefer?

What a float cannot do is to represent a decimal fractional number
(e.g. 1.1) exactly. If we need that, we cannot use floats. A notable
example is monetary computations, it covers 99% of the use for decimal
numbers in computers. For this reason, we should never use floats to
add 10 cents to a dollar. The use of decimals for monetary
calculations is mandatory.
That last sentence is patent nonsense, and completely untrue. Many
satisfactory financial applications have been written using only
floating-point arithmetic. Indeed I believe the accountant's Swiss army
knife, the Excel spreadsheet, uses floating-point numbers exclusively.
This is true, although Excel munges it's FP to provide "expected" results.

It depends on what you consider a "financial" application though.
Excel, while in extremely broad use, is not used to implement any of
the systems which actually "define" money, like the back end financial
systems at banks and credit unions.

In my experience, by far the most common method of calculating
financial numbers is actually using integer amounts, and then applying
well-defined rounding rules which I can't be bothered to look up the
name for.

For what it's worth, the work that I do with money (which is
middleware doing data transport, not calculations or billing) uses
either string representations or fixed point.
What you say about floating-point have speed advantages is true, but you
go too far in claiming that decimal arithmetic is mandatory for monetary
calculations. That's about as sensible as saying that base 12 and base
20 arithmetic units were required to calculate in pounds, shillings and
pence.
I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
Aug 31 '07 #8
On Aug 31, 5:28 pm, "Chris Mellon" <arka...@gmail.comwrote:
On 8/31/07, Steve Holden <st...@holdenweb.comwrote:
sturlamolden wrote:
On 31 Aug, 02:12, Wildemar Wildenburger
<lasses_w...@klapptsowieso.netwrote:
>I've heard (ok, read) that several times now and I understand the
>argument. But what use is there for floats, then? When is it OK to use them?
There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.
Would you care to give an example?
There are fractions that
can be exactly represented by decimals that cannot be exactly
represented by floats.
Which one is better? Which do we prefer?
What a float cannot do is to represent a decimal fractional number
(e.g. 1.1) exactly. If we need that, we cannot use floats. A notable
example is monetary computations, it covers 99% of the use for decimal
numbers in computers. For this reason, we should never use floats to
add 10 cents to a dollar. The use of decimals for monetary
calculations is mandatory.
That last sentence is patent nonsense, and completely untrue. Many
satisfactory financial applications have been written using only
floating-point arithmetic. Indeed I believe the accountant's Swiss army
knife, the Excel spreadsheet, uses floating-point numbers exclusively.

This is true, although Excel munges it's FP to provide "expected" results.

It depends on what you consider a "financial" application though.
Excel, while in extremely broad use, is not used to implement any of
the systems which actually "define" money, like the back end financial
systems at banks and credit unions.

In my experience, by far the most common method of calculating
financial numbers is actually using integer amounts, and then applying
well-defined rounding rules which I can't be bothered to look up the
name for.

For what it's worth, the work that I do with money (which is
middleware doing data transport, not calculations or billing) uses
either string representations or fixed point.
What you say about floating-point have speed advantages is true, but you
go too far in claiming that decimal arithmetic is mandatory for monetary
calculations. That's about as sensible as saying that base 12 and base
20 arithmetic units were required to calculate in pounds, shillings and
pence.

I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
FYI, 1 pound 4 shillings was 1.20 pounds; 1.333... pounds was 1 pound
6 shillings 8 pence. I think...

Aug 31 '07 #9
In article <ma**************************************@python.o rg>,
Chris Mellon <ar*****@gmail.comwrote:
I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
When I worked on the British Railways National Payroll system, about 35
years ago, we, in common with many large users, wrote our system to deal
with integer amounts of pennies, and converted to pounds, shillings and
pence in the output part of the system.

--
David Wild using RISC OS on broadband
www.davidhwild.me.uk
Aug 31 '07 #10
Chris Mellon wrote:
On 8/31/07, Steve Holden <st***@holdenweb.comwrote:
>sturlamolden wrote:
>>On 31 Aug, 02:12, Wildemar Wildenburger
<lasses_w...@klapptsowieso.netwrote:

I've heard (ok, read) that several times now and I understand the
argument. But what use is there for floats, then? When is it OK to use them?
There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.
Would you care to give an example?
>>There are fractions that
can be exactly represented by decimals that cannot be exactly
represented by floats.

Which one is better? Which do we prefer?

What a float cannot do is to represent a decimal fractional number
(e.g. 1.1) exactly. If we need that, we cannot use floats. A notable
example is monetary computations, it covers 99% of the use for decimal
numbers in computers. For this reason, we should never use floats to
add 10 cents to a dollar. The use of decimals for monetary
calculations is mandatory.
That last sentence is patent nonsense, and completely untrue. Many
satisfactory financial applications have been written using only
floating-point arithmetic. Indeed I believe the accountant's Swiss army
knife, the Excel spreadsheet, uses floating-point numbers exclusively.
This is true, although Excel munges it's FP to provide "expected" results.

It depends on what you consider a "financial" application though.
Excel, while in extremely broad use, is not used to implement any of
the systems which actually "define" money, like the back end financial
systems at banks and credit unions.

In my experience, by far the most common method of calculating
financial numbers is actually using integer amounts, and then applying
well-defined rounding rules which I can't be bothered to look up the
name for.

For what it's worth, the work that I do with money (which is
middleware doing data transport, not calculations or billing) uses
either string representations or fixed point.
>What you say about floating-point have speed advantages is true, but you
go too far in claiming that decimal arithmetic is mandatory for monetary
calculations. That's about as sensible as saying that base 12 and base
20 arithmetic units were required to calculate in pounds, shillings and
pence.

I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
There is much in what you say (which, I am happy to note, doesn't really
contradict much of what I wrote). While I agree that Excel isn't a
fundamental component of back-end financial systems you might be
surprised at just how many people rely on its "currency" cells for
financial applications, albeit of a more lightweight kind.

You let yourself down just a little right at the end by not knowing the
intricacies of the old sterling currency - since there were twenty
shillings to the pound and twelve pennies to a shilling that would have
been £1.2. However, you are correct in assuming that nobody tried to
represent £1 3s. 4d. as 23.333... shillings.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 31 '07 #11
On Aug 31, 5:39 pm, David H Wild <dhw...@talktalk.netwrote:
In article <mailman.218.1188577696.28954.python-l...@python.org>,
Chris Mellon <arka...@gmail.comwrote:
I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.

When I worked on the British Railways National Payroll system, about 35
years ago, we, in common with many large users, wrote our system to deal
with integer amounts of pennies, and converted to pounds, shillings and
pence in the output part of the system.
So you never handled halfpennies?

Aug 31 '07 #12
MRAB wrote:
On Aug 31, 5:39 pm, David H Wild <dhw...@talktalk.netwrote:
>In article <mailman.218.1188577696.28954.python-l...@python.org>,
Chris Mellon <arka...@gmail.comwrote:
>>I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
When I worked on the British Railways National Payroll system, about 35
years ago, we, in common with many large users, wrote our system to deal
with integer amounts of pennies, and converted to pounds, shillings and
pence in the output part of the system.
So you never handled halfpennies?
Nobody was paid to the ha'penny. You could spend them in the shops, but
payroll systems didn't use them. I am happy to say that I didn't become
involved in financial programming until after decimalization (February
1971, IIRC - I was in Sweden at the time).

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 31 '07 #13
In article <11**********************@o80g2000hse.googlegroups .com>,
MRAB <go****@mrabarnett.plus.comwrote:
When I worked on the British Railways National Payroll system, about
35 years ago, we, in common with many large users, wrote our system to
deal with integer amounts of pennies, and converted to pounds,
shillings and pence in the output part of the system.
So you never handled halfpennies?
Halfpennies had disappeared from the BR accounting system before the first
use of computers for accounting work.

--
David Wild using RISC OS on broadband
www.davidhwild.me.uk
Aug 31 '07 #14
On Sep 1, 4:58 am, MRAB <goo...@mrabarnett.plus.comwrote:
On Aug 31, 5:39 pm, David H Wild <dhw...@talktalk.netwrote:In article <mailman.218.1188577696.28954.python-l...@python.org>,
Chris Mellon <arka...@gmail.comwrote:
I believe that to the degree that "real" accounting was done in those
currencies it did in fact use non-decimal bases. Just as people don't
use decimal time values (except us crazy computer folk), you're write
1 pound 4 shillings, not 1.333... pounds.
When I worked on the British Railways National Payroll system, about 35
years ago, we, in common with many large users, wrote our system to deal
with integer amounts of pennies, and converted to pounds, shillings and
pence in the output part of the system.

So you never handled halfpennies?
Or farthings?

Aug 31 '07 #15
In message <11*********************@50g2000hsm.googlegroups.c om>,
sturlamolden wrote:
There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.
There are no such.
Sep 1 '07 #16
On 2007-09-01, Lawrence D'Oliveiro <ld*@geek-central.gen.new_zealandwrote:
In message <11*********************@50g2000hsm.googlegroups.c om>,
sturlamolden wrote:
>There are fractions that can be exactly represented by floats that
cannot be exactly represented by decimals.

There are no such.
In that statement does "float" mean finite-length base-2 FP and
"decimal" mean finite-length base-10 FP?

--
Grant Edwards grante Yow! My LESLIE GORE record
at is BROKEN...
visi.com
Sep 1 '07 #17

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

Similar topics

5
by: Jørgen Cederberg | last post by:
Hi, using Python 2.2.1 on Windows and QNX I'm having trouble understandig why int() raises a ValueError exception upon converting strings. >>> int('-10') -10 >>> int('10') 10 >>> int(10.1)
50
by: dataangel | last post by:
I wrote a function to compare whether two strings are "similar" because I'm using python to make a small text adventure engine and I want to it to be responsive to slight mispellings, like...
12
by: BGP | last post by:
I am working on a WIN32 API app using devc++4992 that will accept Dow Jones/NASDAQ/etc. stock prices as input, parse them, and do things with it. The user can just cut and paste back prices into a...
8
by: Madhusudan Singh | last post by:
Is it possible to convert a very long list of strings to a list of floats in a single statement ? I have tried float(x) and float(x) but neither work. I guess I would have to write a loop if...
7
by: MeganTSU | last post by:
Hey yall! I am trying to get this program finished for class.... It says that you are suppposed to write a program that will display a check formatted out put (the output looks like a check). I got...
9
by: bdog4 | last post by:
I want to validate a number to so that they can only input $2.00, 5.00, 7.00, 50.00 etc... I don't wan them to be able to put cents on the amount. It can either either be 2 or 2.00 Any ideas on...
6
by: Chad | last post by:
I would like to remove the decimal but still show the cents using sprintf. char empheader; double totalwage = 123.45; sprintf(empheader, "%.2f", totalwage);
2
by: SergioQ | last post by:
Hi all, am trying to show a dollar figure on my webpage, but defining this for the cents value: font-size: 80%; vertical-align: super; just isn't cutting it! Is there a way to reduce the...
3
by: canabatz | last post by:
i need help creating a from for input price i want two separate fields to hold dollars and cents ,and when i press on submit the all price will be sent as: lets say 12.45 how can i do it ,im...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.