0

I'm trying to make a rounding function in Python to make proper significant figures but I don't know how to remove the quotes from the answer, an ex. is '156.70', I want to have the number with 2 decimal place precision, and round(156.70,2) returns 156.7.

I have tried this: format(round(156.70,2),'.2f'), but it places the answer in single quotes like I stated above. Is there a way to round directly with the floating point zero, or is there a way to remove the quotes?

I have also tried the strip command which does not remove the quotes.

I also tried converting the answer (156.70) to a numpy array to remove the quotes the following way:

ares1 = np.array(format(round(ans,2),".2f"))
values = ares1.item().split(' ')
ares = np.asarray(values, dtype='float')

Where 'ans' is the value 156.7 I want to round to two precision points. Thanks for any help.

  • Not sure what type you are getting. Can you try printing `type(round(156.70,2))`, or at least `type()`, with whatever value you are getting inside the paranthesis? – Krishnan Shankar Feb 22 '22 at 04:09
  • I can print the value without the quotes, but I need to store it in a variable without the quotes. – jauanjennings15 Feb 22 '22 at 18:40
  • By default, the variable should save as a float (number with decimals), not a string. Can you tell me what the output is of the above command? – Krishnan Shankar Feb 22 '22 at 22:22
  • it will output float, but the result of 'round(156.70,2)' will just leave 156.7, i want to keep the zero for precision – jauanjennings15 Feb 25 '22 at 17:16
  • The quotes aren't part of the value; they're just part of the string representation of the value. – chepner Feb 25 '22 at 19:40

1 Answers1

0

Precision doesn't work in programming as it works in real life. By default, numbers have infinite precision, and any decimal places after the defined decimal places will be zeroes. So, your number 156.7 is the same as 156.70 and 156.7000, as they will all be stored identically in memory.

Now with that out of the way, you can definitely "format" the number when outputting it. That will not edit the actual stored value, but will give you a String representation of the number for display purposes only. For that, I'll refer you to this StackOverflow question.

Krishnan Shankar
  • 780
  • 9
  • 29
  • Not sure what you mean by "in real life", but the numbers 156.7, 156.70 and 156.7000 are the same number in any context, not only in programming languages. – kaya3 Feb 25 '22 at 19:40
  • By "real life", I'm referring to scientific calculations where precision is important. For example, in Chemistry or Physics applications. – Krishnan Shankar Feb 25 '22 at 19:42
  • 1
    @KrishnanShankar If you are talking about precision, that's not about actual numbers. It's about a numerical shorthand for sets of equivalent numbers. (156.7 could be anything between 156.65 and 156.74; 156.70 could be anything between 156.695 and 156.704, etc.) – chepner Feb 25 '22 at 19:43