1

currently I am developing a program which helps user to adjust the significant figures. Hereby, I used following codes to split decimal numbers by [integer, ., decimal] format using split('.')

len_number1 = (str(number1)).split('.')

when I enter the value of 1.3333 it successfully separate numbers into ['1', '.', '3333'] but when I enter the value of 0.000043 it shows the result of ['4', '3e-05'] whereby I need to get the result of ['0', '.', '000043']

Is there any ways to solve such problem?

1 Answers1

2

First, when you do str(0.43).split('.') you will get ['0','43'] not ['0','.', '43']. The problem is the casting function str(), because the string format of these decimal numbers, as @MarkMeyer said, is in a scientific notation, that means str(0.000043) will return you '4.3e-05'. Even print(0.000043) will give you something like 4.3e-05 too. You can try something like this to replace that function:

import decimal

dec = decimal.Context()

dec.prec = 20  #this gives us a precition of 20 decimals

def num_to_str(n):

    dec1 = dec.create_decimal(repr(n))  
    return format(dec1, 'n')

print(num_to_str(0.0000043).split('.'))
>>>['0','0000043']

If you want to get ['0','.', '0000043'], you could use insert(), since you will only add one '.' at index 1. You could try

num = num_to_str(0.0000043).split('.')
num.insert(1,'.')
print(num)
>>>['0','.', '0000043']

Checkout the documentation of decimal, repr() and split() for more info.

MrNobody33
  • 6,413
  • 7
  • 19
  • is it impossible to make 0.000043 into ['4', '000043'] using split? – Jung Jae Won Jun 08 '20 at 01:52
  • The problem isn't `split()` @JungJaeWon. It's that you need to turn the number into a string before calling split and `str(0.000043)` is `'4.3e-05'` – Mark Jun 08 '20 at 01:54
  • Yeah that´s right. So here is a trick to do this `str()` casting function for get the result you are looking for. – MrNobody33 Jun 08 '20 at 02:04
  • I thought making number1 as str(number1) will make number1 into string format. it isn't work in such way is it? – Jung Jae Won Jun 08 '20 at 02:04
  • @JungJaeWon see the answer [here](https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa). – ywbaek Jun 08 '20 at 02:06
  • Yeah that's right, `str(n)` will convert `n` into a string. The thing is that the string format of these decimal numbers, as @MarkMeyer said, is in a scientific notation, that means `str(0.000043)` will return you `'4.3e-05'`. You can check this and another different string casting functions in these [link](https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa). – MrNobody33 Jun 08 '20 at 02:20