Convert from decimal to fractional inches (string)

Hi there, just wanted to share this piece of code. As I need to do this a lot it might be useful to someone who is not familiar with coding.
At first, I was using the spring nodes one that is great but I had to add a lot of nodes to it to get to this.
So this simple python node will give you a string with your fractional inches round down to a predefined approximation.

# Enable Python support and load DesignScript library
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN
# Place your code below this line
# Data imput definitions
n=IN[0] #Numbers to be converted
app=IN[1] #Approximation i.E = 1/8" = 0.125 decimal. **** In Decimal ****
#The result array
r=[]
#If approximation is not defined, default it to 0.125 [1/8"]
if not app:
	app = 0.125
#Check to see if your imput have a single number or a list
if type(n) is float:
	r.append(str((n).as_integer_ratio()[0])+"/"+str((n).as_integer_ratio()[1])+"\"")

#If it is a single number
else:
	for e in n:
		b = e - int(e)
		length = len(str(e))
		round(b, 3)
		if b < app:
			r.append(str(int(e))+"\"")
		else:
			if (b%app) > 0:
				c=(int(b/app)*app).as_integer_ratio()
				d=str(c[0])+"/"+str(c[1])+"\""
				
				r.append(str(int(e))+" "+d)	

# Assign your output to the OUT variable.
OUT = r
6 Likes

hey how does it reply to a list to decimal numbers?
its giving me result for only 1st decimal number in a list
image

can you show the code of this?

as_integer_ratio is built-in python method

if someone need some basic functionality to convert from decimal inches to fractional i made something like that

from decimal import Decimal
from math import floor

numbers = [1.25, 1.5, 1.75, 0.75, 12.25, 8.5, 0.5, 4.25]


def convert_decimal_to_rational(number):
    natural_part = floor(number)  # Get whole number part
    fractional_part = Decimal(str(number - natural_part))  # Cast as string for proper fraction
    nominator, denominator = fractional_part.as_integer_ratio()
    if nominator == 0:
        rational_number = str(natural_part)
    elif natural_part == 0:
        rational_number = "{nominator}/{denominator}".format(
            nominator=nominator,
            denominator=denominator
        )
    else:
        rational_number = "{naturalPart} {nominator}/{denominator}".format(
            naturalPart=natural_part,
            nominator=nominator,
            denominator=denominator
        )
    return rational_number


converted_numbers = list(map(convert_decimal_to_rational, numbers))