I am trying to write a program to help me with a lab for a class I am taking. It is supposed to calculate force, energy, work done, etc. I am trying to find a way to round all numbers in it to 3 sig figs. I am not sure how to write it to automatically round off if it is more than or less than 0 . Is there a way that I can do that? I need these numbers to round off this way: 0.13133 rounds to 0.131, 0.0003435 rounds off to 0.000344 1232 rounds off to 1230, and 15363334 rounds off to 15400000.
Asked
Active
Viewed 64 times
-1
-
2Duplicate of [How to round a number to significant figures in Python](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python) – Martin Nov 21 '19 at 13:18
-
I looked at that one, but that is not what I need. – Preston Nov 21 '19 at 13:18
-
Could you clarify how it doesn't answer your question? – Martin Nov 21 '19 at 13:21
-
I'm closing this because there is nothing in the question to indicate that it isn't a perfect duplicate, and because you didn't follow https://stackoverflow.com/help/how-to-ask – Mad Physicist Nov 21 '19 at 13:24
1 Answers
-1
You need the built in round function.
x = 1.23456
y = round(i,3)
print(y)
# This will print 1.235

Rashid 'Lee' Ibrahim
- 1,357
- 1
- 9
- 21
-
Unfortunately for numbers such as 1.1 this will not return `1.10` which is the number to 3 significant figures. – Martin Nov 21 '19 at 13:21
-
@Martin unfortunately 1.10 is not a valid number in python (or most languages). Python always will automatically round the last 0 off. If you store it as a string, then you can put that 0 on it, but then you can perform basic math on the number. – Rashid 'Lee' Ibrahim Nov 21 '19 at 14:56
-