Skip to content
Advertisement

How to round a number to significant figures in Python

I need to round a float to be displayed in a UI. e.g, to one significant figure:

JavaScript

Is there a nice way to do this using the Python library, or do I have to write it myself?

Advertisement

Answer

You can use negative numbers to round integers:

JavaScript

Thus if you need only most significant digit:

JavaScript

You’ll probably have to take care of turning float to integer if it’s bigger than 1.

Advertisement