Python 2.7 を使用して、数値を 10 桁ではなく小数点以下 2 桁に丸めるにはどうすればよいですか?
print "financial return of outcome 1 =","$"+str(out1)
Python 2.7 を使用して、数値を 10 桁ではなく小数点以下 2 桁に丸めるにはどうすればよいですか?
print "financial return of outcome 1 =","$"+str(out1)
組み込み関数を使用しますround()
。
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
または組み込み関数format()
:
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
または新しいスタイルの文字列フォーマット:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
または古いスタイルの文字列フォーマット:
>>> "%.2f" % (1.679)
'1.68'
ヘルプround
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
あなたは財務数値について話しているので、浮動小数点演算を使用したくありません。Decimal を使用したほうがよいでしょう。
>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
new-style を使用したテキスト出力フォーマットformat()
(デフォルトは半偶数丸め):
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
浮動小数点の不正確さによる丸めの違いを参照してください。
>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2) # This converts back to float (wrong)
33.51
>>> Decimal(33.505) # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
財務値を丸める適切な方法:
>>> Decimal("33.505").quantize(Decimal("0.01")) # Half-even rounding by default
Decimal('33.50')
異なるトランザクションで他のタイプの丸めを使用することも一般的です。
>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
リターンの結果をシミュレートしている場合は、セントの端数を支払う/受け取ることも、セントの端数を超える利息を受け取ることもできないため、各利息期間で四捨五入する必要があることに注意してください。シミュレーションでは、固有の不確実性のために浮動小数点を使用するのが一般的ですが、そうする場合は常にエラーがあることに注意してください。このため、固定金利の投資でさえ、リターンが少し異なる場合があります。
も使用できますstr.format()
。
>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23
ペニー/整数を扱う場合。115 ($1.15 など) やその他の数字で問題が発生します。
Integer を Float に変換する関数がありました。
...
return float(115 * 0.01)
それはほとんどの場合うまくいきましたが、時々 のようなものを返します1.1500000000000001
。
だから私は自分の関数をこのように返すように変更しました...
...
return float(format(115 * 0.01, '.2f'))
そしてそれは戻り1.15
ます。'1.15'
または(文字列ではなく1.1500000000000001
浮動小数点数を返します)
これはGoogleでの最初の結果であるため、このシナリオで何をしたかを思い出せるように、主にこれを投稿しています。
print "financial return of outcome 1 = $%.2f" % (out1)