Search notes:

Python standard library: decimal

decimal is a replacement for the float type when precision is important, such as in financial applications.

Parsing JSON floats

#!/usr/bin/env python3

import json

def totalValue(obj):
    total = 0
    for x in obj:
        val = x['val']
        print(f'val = {format(val, ".20f")}')
        total = total + x['val']
    
    print(f'total: {total}')

jsonTxt = '''
[
  { "id": 1, "val": 0.1        },
  { "id": 2, "val": 0.1        },
  { "id": 3, "val": 0.1        },
  { "id": 4, "val": 0.00000001 }
]
'''

jsonObj = json.loads(jsonTxt)
print(json.dumps(jsonObj, indent=3))

totalValue(jsonObj)


print('-------------------------')

import decimal

class decenc(json.JSONEncoder): 
    def default(self, obj): 
      if isinstance(obj, decimal.Decimal): 
         return format(obj, '.8f') 
      return super().default(obj) 

# decimal.getcontext().prec = 9
jsonObj = json.loads(jsonTxt, parse_float=decimal.Decimal)
print(json.dumps(jsonObj, indent=3, cls=decenc))

totalValue(jsonObj)
The output of the script is
[
   {
      "id": 1,
      "val": 0.1
   },
   {
      "id": 2,
      "val": 0.1
   },
   {
      "id": 3,
      "val": 0.1
   },
   {
      "id": 4,
      "val": 1e-08
   }
]
val = 0.10000000000000000555
val = 0.10000000000000000555
val = 0.10000000000000000555
val = 0.00000001000000000000
total: 0.30000001000000004
-------------------------
[
   {
      "id": 1,
      "val": "0.10000000"
   },
   {
      "id": 2,
      "val": "0.10000000"
   },
   {
      "id": 3,
      "val": "0.10000000"
   },
   {
      "id": 4,
      "val": "0.00000001"
   }
]
val = 0.10000000000000000000
val = 0.10000000000000000000
val = 0.10000000000000000000
val = 0.00000001000000000000
total: 0.30000001

See also

standard library

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:51 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(51): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(66): id_of(Object(PDO), 'uri', '/notes/developm...') #2 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758191782, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #3 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/standard-library/decimal/index(132): insert_webrequest() #4 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 51