0

I have a np array freq_vector filled with floating numbers. For example freq_vector[0][0] is 200.00000000000003

I want to limit it to 4 decimals, then convert it to string for other usage.

When I do round(freq_vector[0][0], 4), the result is 200.0, rather than 200.0000

How can I get 200.0000?

martineau
  • 119,623
  • 25
  • 170
  • 301
Echo
  • 667
  • 3
  • 8
  • 19
  • `200.0` is the proper result of the rounding. You will only get `200.0000` if you use string formatters such as `'{0:.4f}'.format(200.00000000000003)`. – Tammo Heeren Sep 13 '19 at 23:12
  • Try `np.array2string(np.array(12.), precision=4, floatmode='fixed')`, or equivalent with `np.set_printoptions`. – hpaulj Sep 14 '19 at 06:30

1 Answers1

1

In Python, 200.0000 is the same as 200.0. Both are floating point numbers with the same value. Since you want to convert them to strings, you can use the format method, such as the following:

"{:.4f}".format(freq_vector[0][0])

Using the round() function is not necessary in this case.

In Python 3, you can use the simpler "f-string" syntax:

f"{freq_vector[0][0]:.4f}"

You can find more information about this feature at PEP 498.

Dan
  • 10,531
  • 2
  • 36
  • 55