我是一個新手學習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)
你真的需要檢查出['Decimal'模塊(HTTP://docs.python。組織/ 2 /庫/ decimal.html)。 – 2013-03-27 15:27:31
謝謝我已經嘗試過了,如上面的代碼所示,但我無法理解足夠的文檔以實現結果,即在小數點右側有2位小數,沒有舍入,必要時使用千位分隔符。 – user1063287 2013-03-28 04:11:55