0

I am trying to write a program for a physics lab that can round off a function to 3 sig figs. I have tried using the round function and other methods mentioned in the other post, but it does not work. The answer to the other question only covers 1 sig fig, not 3. I need it to float when it rounds off numbers. For example, 0.4324 rounds to .432, 0.0002443 rounds to .000244, and 132300 rounds to 132000. I don't want it to print the value, but instead round it and then store it in a variable, as I need it to be rounded off at intermediate steps

 m = float(input("Enter mass: "))
a = float(input("Enter acceleration: "))
i = m*a         
n = 3
print('{:g}'.format(float('{:.3g}'.format(i))))

that is the program I wrote to calculate force to 3 sig figs. This is the output

Enter mass: 4523
Enter acceleration: 2345
1.06e+07
Preston
  • 1
  • 1
  • 2
  • you mean like 47.534534 to 47.535? – nonamer92 Nov 22 '19 at 14:17
  • 1
    Does this answer your question? [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) - in particular the answer by [indgar](https://stackoverflow.com/a/3413529/12366110) or [Falken](https://stackoverflow.com/a/48812729/12366110) – CDJB Nov 22 '19 at 14:18
  • This question does not answer it – Preston Nov 22 '19 at 14:18
  • ranifisch, this is exactly what I want to do. – Preston Nov 22 '19 at 14:19
  • What specific difficulties do you have with the answers there? – CDJB Nov 22 '19 at 14:19
  • It also covers using another package, which I cannot install. I tried using the round_to_3 function, but it gave me a name error – Preston Nov 22 '19 at 14:25
  • 1
    `round(0.0002443, 6)`? It yields `Out[1]: 0.000244` like you wanted. – Nicolas Gervais Nov 22 '19 at 14:28

2 Answers2

2

As mentioned in this post, you can use float('%.3g' % i). This gives a float (which gets automatically converted to string if you print it).

If you want to dynamically control the number of digits, you can introduce a little function that first creates a formatting string.

Some tests:

def round_to_n_digits(num, n=3):
    formatstr = '%.'+str(n)+'g'
    return float(formatstr % num)

i = 4523*2345
print(float('%.3g' % i))

a = [round_to_n_digits(4523*2345, 5),
     round_to_n_digits(123456789),
     round_to_n_digits(0.0002443),
     round_to_n_digits(0.4324)]
print (a)

Output:

10600000.0
[10606000.0, 123000000.0, 0.000244, 0.432]
JohanC
  • 71,591
  • 8
  • 33
  • 66
0

For 3 s.f.:

>>> print('{:g}'.format(float('{:.3g}'.format(12.345))))
12.3

From here.

CDJB
  • 14,043
  • 5
  • 29
  • 55