Emilio
Emilio

Reputation: 45

How to split a number at decimal point to make 2 strings?

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

Upvotes: 0

Views: 1281

Answers (3)

AboAmmar
AboAmmar

Reputation: 5559

Input the radius as float and partition it into whole and frac and print the outputs you want from them.

import math
radius = float(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
    whole = int(fiveDivide)
    print(f'The number of 5KG Bags is: {whole}')
    frac = fiveDivide - whole
    print(f'The number of 1KG Bags is: {math.ceil(5*frac)}')

Upvotes: 0

ljmc
ljmc

Reputation: 5315

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

Or with numbers.

pi = 3.14

n = int(pi)
d = pi - n

print(str(n))  # 3
print(str(d))  # 0.14000000000000012

Upvotes: 4

Spirit Pony
Spirit Pony

Reputation: 148

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

Upvotes: 3

Related Questions