2 people like it.

Mixed number

A function to calculate 'mixed numbers' - eg. 1 1/8. (With fix to reduce the fractional part to its lowest terms)

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
let toMixedNumber num denom divisor =
    let a = num / denom * (float)divisor
    let b = (int)(round(a))
    let c = b / divisor
    let d = b % divisor
    match c, d with
    | 0, 0 -> sprintf "0"
    | 0, d -> sprintf "%i/%i" d divisor
    | c, 0 -> sprintf "%i" c
    | c, d -> sprintf "%i %i/%i" c d divisor

// Example:
//
// [0. .. (1./3.) .. 32.] |> List.map (fun x -> toMixedNumber x 1. 3)
//
//  ["0"; "1/3"; "2/3"; "1"; "1 1/3"; "1 2/3"; "2"; "2 1/3"; "2 2/3"; "3";
//   "3 1/3"; "3 2/3"; "4"; "4 1/3"; "4 2/3"; "5"; "5 1/3"; "5 2/3"; "6";
//   "6 1/3"; "6 2/3"; "7"; "7 1/3"; "7 2/3"; "8"; "8 1/3"; "8 2/3"; "9";
//   "9 1/3"; "9 2/3"; "10"; "10 1/3"; "10 2/3"; "11"; "11 1/3"; "11 2/3"; "12";
//   "12 1/3"; "12 2/3"; "13"; "13 1/3"; "13 2/3"; "14"; "14 1/3"; "14 2/3";
//   "15"; "15 1/3"; "15 2/3"; "16"; "16 1/3"; "16 2/3"; "17"; "17 1/3";
//   "17 2/3"; "18"; "18 1/3"; "18 2/3"; "19"; "19 1/3"; "19 2/3"; "20";
//   "20 1/3"; "20 2/3"; "21"; "21 1/3"; "21 2/3"; "22"; "22 1/3"; "22 2/3";
//   "23"; "23 1/3"; "23 2/3"; "24"; "24 1/3"; "24 2/3"; "25"; "25 1/3";
//   "25 2/3"; "26"; "26 1/3"; "26 2/3"; "27"; "27 1/3"; "27 2/3"; "28";
//   "28 1/3"; "28 2/3"; "29"; "29 1/3"; "29 2/3"; "30"; "30 1/3"; "30 2/3";
//   "31"; "31 1/3"; "31 2/3"; "32"]
val toMixedNumber : num:float -> denom:float -> divisor:int -> string

Full name: Script.toMixedNumber
val num : float
val denom : float
val divisor : int
val a : float
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
val b : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val round : value:'T -> 'T (requires member Round)

Full name: Microsoft.FSharp.Core.Operators.round
val c : int
val d : int
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/9t
Posted:12 years ago
Author:Kit Eason
Tags: fractions , mixed numbers