1

I'm trying to convert strings of numbers that come from the output of another program into floating point numbers with two forced decimal places (including trailing zeros).

Right now I'm converting the strings to floats, then separately specifying precision (two decimal places), then converting back to float to do numeral comparisons on later.

# convert to float
float1 = float(output_string[6])

# this doesn't guarantee two decimal places in my output
# eg: -36.55, -36.55, -40.34, -36.55, -35.7 (no trailing zero on the last number)
nice_float = float('{0:.2f}'.format(float1))

# this works but then I later need to convert back into a float
# string->float->string->float is not super clean
nice_string = '{0:.2f}'.format(float1)

Edit for clarity: I have a problem with the display in that I need that to show exactly two decimal places.

Is there a way to convert a string to a floating point number rounded to two decimal places that's cleaner than my implementation which involves converting a string to a float, then the float back into a formatted string?

gravytrain
  • 73
  • 5
  • I'm a little unclear on what you mean by "floating point number with specific precision". `float` is a pre-defined type; you don't get to specify the precision. You can format a string to have a "display image" with that precision, and then convert that to the nearest `float` value. Do you nave a problem with the display?d string, or with the internal value? – Prune Jul 29 '19 at 23:43
  • Sorry for being unclear, I have a problem with the display in that I need that to show exactly two decimal places. – gravytrain Jul 29 '19 at 23:48
  • Exact(?) duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – Tomerikoo Jul 30 '19 at 00:01
  • Not a duplicate as I'm starting out with strings, so I guess the question I'm asking is: is there a way to convert a string to a floating point number rounded to two decimal places that's cleaner than my implementation which involves converting a string to a float, then the float back into a formatted string. – gravytrain Jul 30 '19 at 00:19
  • Displaying the number rounded to two significant figures is straightforward, just as you've done it. Usual practice is to maintain the `float` at full precision; when you print, you specify the precision you want, just as you've done. Where are you getting a float value or a printed value that doesn't fit your needs? [Minimal, complete, verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) applies here. – Prune Jul 30 '19 at 15:35
  • Similar to my example above: `str = '-36.8'`, `float1 = float(str)`, `nice_float = float('{0:.2f}'.format(float1))`, `print(nice_float)` produces `-36.8` (no trailing zero). – gravytrain Jul 30 '19 at 17:52

0 Answers0