File: util_decimal.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (34 lines) | stat: -rw-r--r-- 757 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- coding: utf-8 -*-

import decimal
import math


def float2dec(f, digits=10):
    parts = str(f).split(".")
    if len(parts) > 1:
        if parts[1][:digits] == "9" * digits:
            f = math.ceil(f)
        elif parts[1][:digits] == "0" * digits:
            f = math.floor(f)
    return decimal.Decimal(str(f))


def stripzeros(n):
    """Strip zeros and convert to decimal.

    Will always return the shortest decimal representation
    (1.0 becomes 1, 1.234567890 becomes 1.23456789).

    """
    if isinstance(n, (float, int)):
        n = "%.10f" % n
    else:
        n = str(n)
    if "." in n:
        n = n.rstrip("0").rstrip(".")
    try:
        n = decimal.Decimal(n)
    except decimal.InvalidOperation:
        pass
    return n