top of page

52. Format a Fraction as "four and one half"

Description

Formats a number and its fraction in the form "four and one half," "four and one fourth," "four and seven eighths," etc.

Code

Explanation
HotDocs does not have a formatting option to spell out the fractional portion of a number (e.g. "one half" or "two-thirds"). This premium computation will. Examples: "four and one half," "four and one fourth," "four and seven eighths," etc.

The one caveat is that the computation must take the number and its fraction from a text string or variable, since a number value does not contain a formatted fraction. To explain, the computation needs to see a fraction (1/2, 3/4, etc.), whereas a number variable contains a decimal (.5, .75, etc.). If you would like to have a decimal (.5) spelled out as a fraction ("one half"), use this computation in conjunction with Computation #0116: Smarter Fraction Formatting. Computation #0116 will format your decimal number as a fraction which can then be fed into this computation.

Code
""
// Has fractional portion
IF FractionStr-t CONTAINS "/"

// Integer portion
SET Temp-n TO POSITION( FractionStr-t, " " )
IF Temp-n > 0
FORMAT(
INTEGER( FIRST( FractionStr-t, Temp-n - 1 )) ,
"nine"
) + " and "
END IF

// Fractional portion
SET Temp-t TO LAST( FractionStr-t, LENGTH( FractionStr-t ) - Temp-n )

IF Temp-t = "1/2"
RESULT + "one half"
ELSE

// Numerator
SET Temp-n TO POSITION( Temp-t, "/" )
RESULT + FORMAT(
INTEGER( FIRST( Temp-t, Temp-n - 1 )) ,
"nine"
)

// Does denominator need to be plural?
IF FIRST( Temp-t, Temp-n - 1 ) = "1"
SET Temp-b TO FALSE
ELSE
SET Temp-b TO TRUE
END IF

// Denominator
RESULT + " " +
FORMAT(
INTEGER( LAST( Temp-t, LENGTH( Temp-t ) - Temp-n )) ,
"ninth"
)

IF Temp-b
RESULT + "s"
END IF

END IF

// Has no fractional portion
ELSE
FORMAT(
INTEGER( FractionStr-t ) ,
"nine"
)
END IF

Explanation

The computation parses the string into an integer portion, numerator portion, and denominator portion, and then converts each into a numerical value and formats it appropriately. The parts are reassembled, and a string is returned with the formatting "nine and two-thirds."

See also, Computation 51: Format a Number as "nine point seven five", 62: "All (100%)", #0116: (Even) Smarter Fraction Formatting, #0150: Decimal Formatter.

©2023 by My Site. Proudly created with Wix.com

  • Facebook
  • Twitter
  • LinkedIn
bottom of page