0

I am trying to work on a random number generator which produces a random number which is to 2dp regardless of whether it needs to be. eg. 2.10 is 2.10 not 2.1, 3 = 3.00

import random

temp_var_4_int = random.randint(2,5) + round(random.random(),2)

print (temp_var_4_int)

It should randomize a number between 2 and 5 and then add a decimal to it which is rounded to 2 decimal places but I keep getting answers such as:

1.2700000000000002 instead of 1.27

I'm not sure why it's throwing this anomaly at me.

Austin
  • 25,759
  • 4
  • 25
  • 48
James Novis
  • 343
  • 5
  • 15
  • 1
    To understand why you're seeing things like `1.2700000000000002`, see: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – sjw Jul 10 '19 at 18:05

4 Answers4

0

assuming you want your numbers in [0, 10] you could just do this:

from random import uniform

r = round(uniform(0, 10), 2)
print(f"{r:3.2f}")

if r = 2.1 the format string will represent it as "2.10"; but for all mathematical purposes the trailing zero has no effect.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0
import random
print("Printing random float number with two decimal places is ",
      round(random.random(), 2))
print("Random float number between 2.5 and 22.5 with two decimal places is ",
      round(random.uniform(2.5,22.5), 2))
Konstantin
  • 133
  • 1
  • 8
Pragati
  • 7
  • 4
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Nic3500 Jul 10 '19 at 23:05
0

Try to use string formatting:

from random import randint, random

temp_var_4_int = round(randint(2,5) + random(), 2)

print(temp_var_4_int)
print(f"{temp_var_4_int:.2f}")

That would output something like:

2.1
2.10

Please note that f-strings works on Python 3.6+

mohd4482
  • 1,788
  • 14
  • 25
  • That's okay but i need it kept as a number not a string as I need to do some maths with the variable – James Novis Jul 10 '19 at 18:19
  • @JamesNovis if you want to show the number formatted it has to be a string especially in cases like the one I showed – mohd4482 Jul 10 '19 at 18:25
0

You can format the float with two digits like:

import random

temp_var_4_int = random.randint(2,5) + round(random.random(),2)
temp_var_4_int = '%.2f' % (temp_var_4_int)
print(temp_var_4_int)

According to this Q&A

(0.1+.02)

will return

0.12000000000000001

and

'%.2f' % (0.1+.02)

will return

'0.12'

Try it if you please and let me know, is another example of the same issue

developer_hatch
  • 15,898
  • 3
  • 42
  • 75