0

I am trying to get a number with exactly 5 numbers after decimal point, no rounding! for example:

2.34567836576 ----> 2.34567

We are allowed to use only string formatting. I only succeeded to do that with rounding unfortunately. Using 3.7 Python Thank you!

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • `float(str(a)[:7])`--->`2.34567` I don't if this is *Pythonic* – Ch3steR Mar 20 '20 at 15:43
  • 1
    Does this answer your question? [Python setting Decimal Place range without rounding?](https://stackoverflow.com/questions/29246455/python-setting-decimal-place-range-without-rounding) – Ch3steR Mar 20 '20 at 15:49
  • it works! but is it string formatting? – Tom Shchori Mar 20 '20 at 15:54
  • Nope. I just typecasted your float to string and took a slice of the string i.e until 5 decimal point and converted it back to float. – Ch3steR Mar 20 '20 at 15:56
  • Note : You need to change the length of the slice based on your number. The above works only for numbers in range 0 to 9.99999... – Ch3steR Mar 20 '20 at 15:59

1 Answers1

0

Just use string formatting.

"{:.5f}".format(232.34567836576)
> '232.34568'

Edit: Here's a super hacky way using mostly string formats:

("{0:." + str(len("{0:.5f}".format(22.34567836576))) +"}").format("{0:f}".format(22.34567836576))
22.34567

I'm not sure what the point of the exercise is. What I'm doing is truncating a string to the length of the (wrongly) rounded, formatted float.

For what I can find, there's no way of plainly formatting it. I'm sorry if this answer is invalid, had I read your rounding thing beforehand, I wouldn't have commented.

Mies van der Lippe
  • 492
  • 1
  • 3
  • 13