0

If i have a float number like float = 51.31876543.

How can I create a new float value selecting the first seven numbers and generating randomly the remain numbers? To obtain something like this:

float = 51.31876 + 3 random numbers
like 51.31876411 or 51.31876739 ...
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Alessio Vacca
  • 31
  • 1
  • 4

3 Answers3

2

you can convert your float number to a string and then add your 3 random numbers.
first, let's see how you can make your random numbers: by using random library. I suggest random.randint().

import random
f = 51.31876543

# now you must choose the first seven numbers that you have in mind.
f_str = str(f)[:8]

# we assume that your number is always a float.
# if you were not sure if it is an integer or a float, you can code this:
if '.' not in f_str:
    f_str.pop()

# now make your random 3 number and add it to your number:
f_str = f_str + str(random.randint(100, 999))

f = float(f_str) # change type from string to float.
FarZad
  • 463
  • 3
  • 19
1

You can use the truncate function defined here to get just the 5 decimal values, multiply it by 100.000, sum with a random int between 100 and 999, divide it by 100.000 and the rounding up to 5 decimal values again.

def truncate(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d+'0'*n)[:n]])

import random
float = 51.31876543
float = truncate(float, 5)
float = float * 10e5
random_3_numbers = random.randint(100,999)
float += random_3_numbers
float /= 10e5
float = truncate(float, 5)

Also, your question is badly tagged. It should contain python and other tags as well.

Lucas Hattori
  • 87
  • 1
  • 8
0

Here is how you can use random.randint():

from random import randint

f = 51.31876543
f = str(f)[:8]
if '.' not in f:
    f.pop()
for _ in range(3):
    f += str(randint(0,9))
print(f)

Output:

51.31876308
Red
  • 26,798
  • 7
  • 36
  • 58