[Tutor] float & string

dman dman@dman.ddts.net
Thu, 30 May 2002 00:42:04 -0500


--8P1HSweYDcXXzwPJ
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, May 29, 2002 at 09:37:26PM +0000, Terje Johan Abrahamsen wrote:
| I have a floating number

| dollar amount?

BAD BAD BAD.  Never use floating point numbers for currency.  The
approximation (necessitated by finite precision) will cause
"inaccuracies" in the amounts your software computes.  Instead store
all currency amounts in (eg for US or Canada) cents rather than
dollars.  Displaying the number as "$240.00" on screen is wholly
different from the internal storage.  For example :

def cheesy_money_print( amt ) :=20
    """ note that better libraries exist for doing this """
    dollars =3D int( amt / 100.0 )  # pull out the dollars part
    cents =3D amt - (dollars*100)  # pull out the cents part
    s =3D "$%d.%.2d" % ( dollars , cents )
    return s

>>> cheesy_money_print( 24000 )
'$240.00'


I call this formatter "cheesy" because it assumes that the local
currency designator is '$' and doesn't really do any error or sanity
checking or anything like that.  It also assumes that you want 2
decimal places in the currency.  A better choice is to use a locales
library to format the strings according to the user's locale settings.

HTH,
-D

--=20

Q: What is the difference betwee open-source and commercial software?
A: If you have a problem with commercial software you can call a phone
   number and they will tell you it might be solved in a future version.
   For open-source sofware there isn't a phone number to call, but you
   get the solution within a day.
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--8P1HSweYDcXXzwPJ
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjz1u6wACgkQO8l8XBKTpRStwQCffr805Bcy2l8+Tdr9A+tBsMgx
KwgAn0bs8akSSjCExR67rqqpVIbitSh5
=+OuJ
-----END PGP SIGNATURE-----

--8P1HSweYDcXXzwPJ--