+ 1

# Is there any other way of rounding off numbers without using 'round' ?

7 Answers

+ 8

# string formatting
x = 1.2345
print(f"{x:.2f}")

+ 8

Levin Mwanganyi ,
as [user id="9509148"]Lisa[/user] already mentioned, you can use an f-string or an other string formatting to get a defined number of decimal places from a float number. in this case a rounding is performed.
but there are also cases where you need to reduce the number of digital places but just cutting without any rounding:
n = 3 # number of decimal places
x = 1.1667
# this version is cutting to n decimal places included a rounding
print(f"{x:.{n}f}") # res: 1.167
# this version is cutting to n decimal places WITHOUT any rounding
print(int(x * (10**n))/(10**n) ) # res: 1.166

+ 4

Depends on the language. (Might be a good idea to put the language in the tag)

+ 2

Do you mean "rounding" ("mathematically") or "rounding off" in terms of cutting off the decimals? For the later, converting the number to an integer might be an option.

+ 2

I mean reducing the number of decimal places from let's say 4 to 2 decimal places

0

Thank you

0

Like the posts before double the expression symbols (**, //) will show up the value and cut decimalplaces

Hot today

What is indentations... ?

6 Votes

Application RAM usage

1 Votes

Showing errors!

2 Votes

About Java McQ

0 Votes

Q. Anna is 18 years old

-2 Votes

int num = 2;
int x = 3;
if(num >= 2) {
if(x > 4) { num = 3; }
else { num = 4; }
}
else {x = 1; }

1 Votes

Balconies Problem in C

0 Votes