valdezt / sigfig

A python module aimed to aid the user with visual display of scientific numbers, i.e. significant figures, rounding, spacing, etc.
12 stars 4 forks source link

Stocks #6

Open RCdiy opened 3 years ago

RCdiy commented 3 years ago

For stock prices I’m trying to display 3 significant figures on an oled display as follows 1234.56 ~ 1230 (no decimal) 123.456 ~ 123 12.3456 ~ 12.3 1.2345 ~ 1.23 0.1234 ~ 0.123 How do I do this without doing 4 checks? For example def my_sigfig(a): x = round(a , sigfig=3) If x >= 100 then result int(x) If x >= 10 then result int(x10)/10 If x >= 1 then result int(x100)/100 If x >= 0.1 then result int(x*1000)/1000

MikeBusuttil commented 3 years ago

Hi RCdiy, you shouldn't have to make any checks, the sigfig library is meant to do that for you. Make sure you have the sigfig library installed (see instructions here: https://sigfig.readthedocs.io/en/latest/install.html ); and make sure you're not using float as the results could be confusing; then you could do the following within your program (without the ">"s):

>>> from sigfig import round
>>> round(1234.56, 3, type=str)
'1230'
>>> round(str(123.456), 3)
'123'
>>> round(str(12.3456), 3)
'12.3'
>>> round(str(1.23456), 3)
'1.23'
>>> round(str(.123456), 3)
'0.123'

Python's default float implementation shown here can make your results appear misleading as it will add zeros after the decimal point in some cases:

>>> from sigfig import round
>>> round(1234.56, 3)
1230.0
>>> round(123.456, 3)
123.0
>>> round(12.3456, 3)
12.3
>>> round(1.23456, 3)
1.23
>>> round(.123456, 3)
0.123

Hope that helps

RCdiy commented 3 years ago

Thanks. I wasn’t using str.