Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

parsing - Keep trailing zeroes in python

I am writing a class to represent money, and one issue I've been running into is that "1.50" != str(1.50). str(1.50) equals 1.5, and alll of a sudden, POOF. 45 cents have vanished and the amount is now 1 dollar and 5 cents. not one dollar and 50 cents. Any way I could prevent str from doing this, or am I doing something wrong? This is Python 2 BTW.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the format method on strings to specify how many decimal places you want to represent:

>>> "{:.2f}".format(1.5)
'1.50'

But even better would be to use the decimal module for representing money, since representation issues with binary floats can give you slightly off results if you're doing arithmetic. The documentation for that module mentions some of those issues specifically - one of the most interesting ones for money applications is:

>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> from decimal import Decimal
>>> Decimal('.1') + Decimal('.1') + Decimal('.1') - Decimal('.3')
Decimal('0.0')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...