0

It's my first week trying to learn how to code.

Rods is input from user so it can be whatever

miles = round(Rods * 0.003125, 20)
print("Distance in Miles = ", miles)

I need this line of code to print 20 decimals. I thought by adding comma 20 it would do so. I then tried looking re-writing it to format{miles: "20.f"}. (Don't remember exactly how the code went)

Any guidance would be appreciated.

Minh-Long Luu
  • 2,393
  • 1
  • 17
  • 39
  • Check out built-in Decimal module here: https://docs.python.org/3/library/decimal.html – lllrnr101 Jan 25 '21 at 06:49
  • Here's a link about floating point representation https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points – user2758526 Jan 25 '21 at 06:51
  • 2
    Does this answer your question? [How to print float to n decimal places including trailing 0s?](https://stackoverflow.com/questions/8568233/how-to-print-float-to-n-decimal-places-including-trailing-0s) – Sebastian Dengler Jan 25 '21 at 06:51
  • I think you should have looked more over internet you would have find plenty solutions ..here's one way print("%.20f"%rods) – Shag Jan 25 '21 at 06:51

3 Answers3

1

Try this snippet:

miles = Rods * 0.003125
print("Distance in Miles = {:.20f}".format(miles))

This code does the calculation first and formats the answer such that it is displayed in 20 decimal places. For displaying only 10 decimal places change to .10f, for 2 decimal places change to .2f and so on.

Keziya
  • 96
  • 5
  • 1
    This should be the answer. @Keziya could you maybe edit your answer to describe what it is you're doing here so the OP can understand it better? – Ryan Barnes Jan 25 '21 at 07:08
0

When calling round() method on floats, the unnecessary leading decimal zeros are not counted, since the number is the same. You can convert the number to string, use .split(".") on it to separate the decimal and whole number example: "3.85".split(".") will return a list whose elements are ["3", "85"] digits = str(num).split(".") Lets take the second element, decimals decimals = digits[1] Then you take the length of second element that is decimals and subtract it from 20. This will be the amount of zeros to add. newDecimals = decimals + (20 - len(decimals)) * "0" Now, use the list from before to form a new number final = digits[0] + "." + newDecimals

Keep in mind that converting it back to a float will remove those zeros.

musava_ribica
  • 476
  • 1
  • 5
  • 18
0

Try following source code :

miles = Rods * 0.003125
miles_formatted_float = "{:.20f}".format(miles)
print("Distance in Miles = "+miles_formatted_float)