ArcticLightning
ArcticLightning

Reputation: 29

Turning a float into an integer without rounding the decimal points

I have a function that makes pseudorandom floats, and I want to turn those into integers, But I don't mean to round them. For Example, If the input is:

1.5323665

Then I want the output to be:

15323665

and not 2 or 1, which is what you get with round() and int().

Upvotes: 0

Views: 990

Answers (4)

ti7
ti7

Reputation: 18792

Rather than creating your own pseudorandom engine, which almost-certainly won't have a good density distribution, especially if you coerce floats to ints in this way, strongly consider using a builtin library for the range you're after!

More specifically, if you don't have a good distribution, you'll likely have extreme or unexplained skew in your data (especially values tending towards some common value)

You'll probably be able to observer this if you graph your data, which can be a great way to understand it!

Take a look at the builtin random library, which offers an integer range function for your convenience

https://docs.python.org/3/library/random.html#random.randint

import random
result = random.randint(lowest_int, highest_int)

Upvotes: 2

Amal K
Amal K

Reputation: 4854

You can first convert the float to a string and then remove the decimal point and convert it back to an int:

x = 1.5323665
n = int(str(x).replace(".", ""))

However, this will not work for large numbers where the string representation defaults to scientific notation. In such cases, you can use string formatting:

n = int(f"{x:f}".replace(".", ""))

This will only work up to 6 decimal places, for larger numbers you have to decide the precision yourself using the {number: .p} syntax where p is the precision:

n = int(f"{1.234567891:.10f}".replace(".", ""))

Upvotes: 2

mahdi hoseyni
mahdi hoseyni

Reputation: 63

x = 1.5323665
y= int (x)
z= str(x-y)[2:]
o = int(len(z))
print(int(x*10**o))

it will return 15323665

Upvotes: 1

Michael
Michael

Reputation: 5335

Convert it to string and remove a dot:

int(str(x).replace('.', ''))

Upvotes: 1

Related Questions