Print number in engineering format

前端 未结 6 1716
陌清茗
陌清茗 2020-12-06 01:22

I am trying to print a number into engineering format with python, but I cannot seem to get it to work. The syntax SEEMS simple enough, but it just doesn\'t work.



        
6条回答
  •  死守一世寂寞
    2020-12-06 02:07

    QuantiPhy is another package that can help you with this. QuantiPhy provides the Quantity class that is used to combine a value and units into one object. It can format the quantity in a variety of ways. Generally people use SI scale factors, but engineering form is also supported. Install with:

    pip3 install quantiphy
    

    You can create a Quantity object starting from a number or a string:

    >>> from quantiphy import Quantity
    >>> q = Quantity(10000000)
    >>> q.render(form='eng')
    '10e6'
    

    By default QuantiPhy uses SI notation, but you can set the default form to 'eng':

    >>> print(q)
    10M
    >>> Quantity.set_prefs(form='eng')
    >>> print(q)
    10e6
    

    Normally you would specify units to a quantity:

    >>> f = Quantity(10_000_000, 'Hz')
    >>> print(f)
    10e6 Hz
    

    Quantity subclasses float, so you can use a quantity anywhere you would use a float.

    QuantiPhy is a powerful package that is well supported and well documented. I encourage you to give it a try.

提交回复
热议问题