1

Edit: I saw the two similar questions but I didn't get my answer.

I want to square some numbers with 4 numbers after the decimal point:

import math
lis=math.sqrt(19)
print("%.4f" % lis)

sqrt(19)=4.35889894 so the output will be:

4.3589

and I want it to be:

4.3588

without rounding up. What do I do?

2 Answers2

1

Use math.floor to always round down. Wrap the final output in math.floor and that will do it.

import math
lis=math.sqrt(19)
print(math.floor(lis * 10000)/10000.0)

returns 4.3588

onlyphantom
  • 8,606
  • 4
  • 44
  • 58
  • I edited the code a bit to gave you that precision of a float. But `math.floor()` do the trick and is easily understandable. – onlyphantom Apr 27 '18 at 12:40
  • Only if you take this too literally and downvote instantly without thinking... See [here](https://stackoverflow.com/questions/29246455/python-setting-decimal-place-range-without-rounding?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Alexander Harnisch Apr 27 '18 at 12:45
  • Yeah no offense taken but @HoseinShendabadi this does exactly what you need and it doesn't feel hackerish at all, so not sure why you downvoted it or didn't want to accept it as an answer? – onlyphantom Apr 27 '18 at 12:49
  • @onlyphantom I'm sorry pal but the code returned "4" to me – Hosein Shendabadi Apr 27 '18 at 12:51
  • hmm @HoseinShendabadi Did you see the edited code that I put up 12 mins ago? `print(math.floor(lis * 10000)/10000.0)` returned exactly 4.3588 - which is what you asked for. – onlyphantom Apr 27 '18 at 12:52
  • @onlyphantom My bad :) . – Hosein Shendabadi Apr 27 '18 at 12:57
0

Well, this is more of a hack

float(str(math.sqrt(19))[:6])

Let me know if this isn't something that solves your problem

Sushant
  • 3,499
  • 3
  • 17
  • 34