我是一个学习 python (2.7.3) 的新手,并且得到了一个简单的计算成本的练习,但很快就对真正能够控制或理解正在产生的结果的“精确性”产生了兴趣。如果我在我的计算机上使用计算器,我会得到我认为我想要的结果(即它们看起来非常具体),但如果我使用 python,我似乎必须非常准确地了解如何将格式信息添加到正在使用的值中,并且打印。
我的问题的简短版本是:
每当我使用返回的货币时,是否有一个简单的解决方案可以使用:
- 小数点右边两位小数
- 不进行四舍五入(即基本上只是“截断”小数点后第二位右侧的任何内容)
- 如有必要,添加千位分隔符
如果有人想运行它来查看结果和变化,我一直在使用解释器(见下面的代码)测试变化。
谢谢你。
# basic entry - both are seen as integers
print 'A: ', 7/3
# test by printing out the types
print 'B: ', type(7)
print 'C: ', type(3)
# this is not necessary as they are already integers
print 'D: ', int(7/3)
# converts the result of 7/3 into a floating number
print 'E: ', float(7/3)
# defines the float version of 7 by the float version of 3
print 'F: ', float(7) / float(3)
# coverts the results of the above into a string and assigns to variable
string_var = str(float(7) / float(3))
# print the string
print 'G: ', string_var
# prints 4 characters of the string, but returns two decimal places
print 'H: ', string_var[:4]
string_var = str(25.8545678888)
# prints 5 characters of the string, but returns two decimal places
print 'I: ',string_var[:5]
# import the locale module
import locale
# sets to user's default settings (don't know what empty quotes are)
locale.setlocale( locale.LC_ALL, '' )
#set an arbitrary float number to a variable
float_var = 25.859
# apply locale.currency formatting
print 'J: ',locale.currency(float_var)
# import the decimal module
from decimal import *
# the decimal version of the variable
print 'K: ',Decimal(float_var)
# divide the decimal version by 2
print 'L: ',Decimal(float_var) / 2
# divide the decimal version by the decimal verson of 2
print 'M: ', Decimal(float_var) / Decimal(2)
# change decimal precision to 6
getcontext().prec = 6
# note there is no change in this value as precision only applied to
# result of calculations, see
#http://stackoverflow.com/questions/6483440/python-decimal-precision
print 'N: ', Decimal(float_var)
# the following equation returns decimal precision to 6 (6 characters displayed)
print 'O: ', Decimal(float_var) / 2
# example of 6 characters printed, not decimal places
# to the right of the decimal
print 'P: ', Decimal(55550) / 130
# if you want to control places to the right of the decimal
# displayed without rounding and show thousand separators if
# necessary ?
编辑:
感谢大家的回复,这是我采用的解决方案,它是所有回复的混合:
def make_it_money(number):
"""
always:
- shows 2 decimal places
- shows thousands separator if necessary
- retains integrity of original var for later re-use
- allows for concise calling
"""
import math
return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))
# tests
var1 = 25.867
var2 = 25.864
var3 = 25.865
var4 = 2500.7869
print make_it_money(var1)
print make_it_money(var2)
print make_it_money(var3)
print make_it_money(var4)