質問

>>> str(1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702)
'1.41421356237'

Is there a way I can make str() record more digits of the number into the string? I don't understand why it truncates by default.

役に立ちましたか?

解決 2

Try this:

>>> from decimal import *
>>> Decimal('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702')
Decimal('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702')

The float literal is truncated by default to fit in the space made available for it (i.e. it's not because of str):

>>> 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702
1.4142135623730951

If you need more decimal places use decimal instead.

他のヒント

Python's floating point numbers use double precision only, which is 64 bits. They simply cannot represent (significantly) more digits than you're seeing.

If you need more, have a look at the built-in decimal module, or the mpmath package.

The Python compiler is truncating; your float literal has more precision than can be represented in a C double. Express the number as a string in the first place if you need more precision.

That's because it's converting to a float. It's not the conversion to the string that's causing it. You should use decimal.Decimal for representing such high precision numbers.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top