0

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
martineau
  • 119,623
  • 25
  • 170
  • 301
Emilio
  • 45
  • 5
  • Does this answer your question? [Splitting a number into the integer and decimal parts](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts) – mkrieger1 Jun 11 '22 at 21:01

3 Answers3

4

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
ljmc
  • 4,830
  • 2
  • 7
  • 26
  • I have done this, however I want to take the answer from your last line of code, times it by 5 and round it up to the nearest whole number. If i try doing that with your code, all it does is print the answer 5 times – Emilio Jun 11 '22 at 21:12
  • That's normal, the `pi_str` variable is a str, why do you want to multiply it again ? – ljmc Jun 11 '22 at 21:14
  • I want to create two strings here. The first is my first answer, so no problem here. However I need to take the remaining decimal numbers from the first answer, times them by 5 and then round them UP to the nearest whole number. – Emilio Jun 11 '22 at 21:16
  • @Emilio please see my edit for doing the same thing with numbers so you can multiply them. – ljmc Jun 11 '22 at 21:20
3
n = 2.743
i, f = str(n).split(".")
print(f"Integer part: {i}, fraction part: {f}")
Spirit Pony
  • 148
  • 7
0

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)}')
AboAmmar
  • 5,439
  • 2
  • 13
  • 24