0

I am trying to use numpy.around to format a vector of floats so that each value has exactly two decimals. However, when the last digit is 0, it automatically omits it.

For example, when I have the following code

import numpy as np
a = np.array([  56.8313253 ,  385.30120482,    6.65060241,  126.62650602,
         85.75903614,  192.72289157,  112.80722892,   10.55421687 ])
np.around(a,decimals=2)

I receive the following result, where the second number has only one digit.

array([  56.83,  385.3 ,    6.65,  126.63,   85.76,  192.72,  112.81,
         10.55])

Is there any way that I can always keep the 0 at the end? This is needed for publication purpose, and adding the 0s by hand is too tedious because I have numerous cases like this.

user3821012
  • 1,291
  • 2
  • 16
  • 27

3 Answers3

2

Use np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) before printing the array.

In [1]: import numpy as np

In [2]: a = np.random.random(20)

In [3]: print(a)
[ 0.78298863  0.09129314  0.04204522  0.04574351  0.76764957  0.58406234
  0.26670654  0.39624515  0.27261618  0.29430686  0.49316331  0.72693718
  0.16535966  0.53017297  0.66432047  0.24194043  0.91635168  0.29603418
  0.07480831  0.67555659]

In [4]: np.set_printoptions(formatter={'float': '{: 0.3f}'.format})

In [5]: print(a)
[ 0.783  0.091  0.042  0.046  0.768  0.584  0.267  0.396  0.273  0.294
  0.493  0.727  0.165  0.530  0.664  0.242  0.916  0.296  0.075  0.676]
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
1

not quite sure what you need for your publication, but if you just need the numbers in some sort of list you can use string formatting like this:

import numpy as np
[  56.8313253 ,  385.30120482,    6.65060241,  126.62650602,
         85.75903614,  192.72289157,  112.80722892,   10.55421687 ])
["{:.2f}".format(x) for x in a]

returns:

['56.83', '385.30', '6.65', '126.63', '85.76', '192.72', '112.81', '10.55']
PdevG
  • 3,427
  • 15
  • 30
0

The decimal module provides one solution:

import numpy as np
from decimal import *

arr = np.array([  56.83,  385.3 ,    6.65,  126.63,   85.76,  192.72,  112.81, 10.55])
arr2 = [str(Decimal(i).quantize(Decimal('.01'))) for i in arr]

# ['56.83', '385.30', '6.65', '126.63', '85.76', '192.72', '112.81', '10.55']
jpp
  • 159,742
  • 34
  • 281
  • 339