Home > OS >  In Python, how can I get a whole number without decimals from math.sqrt?
In Python, how can I get a whole number without decimals from math.sqrt?

Time:05-01

import math

a = math.sqrt(25)

print(a)

My output is 5.0, how can I get a 5 (whole number) instead?

CodePudding user response:

You have to check and explicitly convert to integer:

if x == (y := int(x)):
    x = y

Or, without the assignment operator:

if x == int(x):
    x = int(x)

As of python 3.8, you can use math.isqrt:

math.isqrt(25)

Keep in mind that this will always return an integer, even if the input is not a perfect square.

CodePudding user response:

In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:

import math

a = math.sqrt(25)
a = int(a) if int(a)==a else a

print(a)

CodePudding user response:

It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?

For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:

print("{:.0f}".format(a))

What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.

This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.


For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).

  • Related