Home > Software design >  Splitting number at decimal point to make 2 strings in Python
Splitting number at decimal point to make 2 strings in Python

Time:06-12

Essentially I would like to split my answer after the decimal point to create two strings. So for example if my answer is 2.743, I would like to create a string for 2, and a string for .743.

I want the answer from fiveDivide to print as one answer, and the decimal points I need to add some more equations to, so I can print another answer. The output will be something like this:

The number of 5KG Bags is: (fiveDivide), 
The number of 1KG Bags is:

Here is a copy of the code I have so far:

radius = int(input("\nPlease enter the radius of the area: "))
if radius <= 75 and radius >= 1:
    circleArea = 3.1416 * (radius ** 2)
    circleKilos = circleArea / 100
    print("The KGs required is: ", circleKilos)
    fiveDivide = circleKilos / 5

CodePudding user response:

There are many ways to do that, but to avoid issues with floating point precision you can start by converting to string and then splitting on the index of the decimal point.

pi = 3.14

pi_str = str(pi)

point_index = pi_str.index(".")

print(pi_str[:point_index])  # 3
print(pi_str[point_index:])  # .14

CodePudding user response:

n = 2.743
i, f = str(n).split(".")
print(f"Integer part: {i}, fraction part: {f}")
  • Related