Skip to content
Advertisement

How to split an unknown number

Picture the following number (here it will be a measure of time) as an output of a given program:

0.000000000123

How would I be able to split it so that I can read it like this:

000 seconds 000 miliseconds 000 microseconds 000 nanoseconds 123 picoseconds

I would like to do this for any ‘unknown’ decimal (comma separated) number.

Thanks!

Advertisement

Answer

Convert your value as a string and format it appropriately. For instance (I’m assuming you always want picoseconds precision):

units=["","milli","micro","nano","pico"]
val = 0.000000000123
s = f'{val:016.12f}'.replace(".","")
x = ""
for i,u in enumerate(units):
    x += f'{s[i*3:i*3+3]:3} {u}seconds '

x
'000 seconds 000 milliseconds 000 microseconds 000 nanoseconds 123 picoseconds '

EDIT

How do the two f-strings work:

The first one converts the value to a string of length 16, with trailing zeros and 12 digits after the decimal point – then the replace removes the point since we don’t need it. So we have a 15-digit string, 3 digits for each unit of measure.

The second one takes triplets of digits and adds to each the prefix (“milli”, “micro”, …) and the words “seconds”. At the end of the loop we have our five triplets with the proper unit of measure added.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement