0

Is it possible to convert the format that comes out of converted(to: UnitVolume.metricCups) into a fraction so the answer is read just like you would from say a cookbook etc.

Example after the conversion is complete I get an answer of 1.5 metric cups, but I would like to see it as 1 1/2 or say 0.333 as 1/3 cup.

Swift documentation doesn't really mention any steps for this that I'm aware of. Thank you.

This is what the storyboard looks like:

UI in Storyboard

let millimeters = Measurement(value: waterResult, unit: UnitVolume.milliliters)
let resultWaterConversion = millimeters.converted(to:UnitVolume.metricCups)
cupsWater.text = "\(resultWaterConversion)"
vacawama
  • 150,663
  • 30
  • 266
  • 294

1 Answers1

0

I was able to solve my issue by using a switch and a little modification with the string values eg "3/4" to get it just right for my needs.

Here is the code i used:

`// MARK:- Conversion to display rice amount in the correct format for readability
    let resultRiceInteger = Int(resultRiceConversion.value)
    let resultRiceFraction = Int(100 * (resultRiceConversion.value - Double(resultRiceInteger))) // To avoid bad effects due to Double

    var decimalTextR = ""
    switch resultRiceFraction {
    case 0...9 : decimalTextR = "" // Now, approximate
    case 10 : decimalTextR = "1/10"  // First when we are very close to real fraction
    case 11 : decimalTextR = "1/9"
    case 12...13 : decimalTextR = "1/8"
    case 14...15 : decimalTextR = "1/7"
    case 16...18 : decimalTextR = "1/6"
    case 19...22 : decimalTextR = "1/5"
    case 23...29 : decimalTextR = "1/4"
    case 30...40 : decimalTextR = "1/3"
    case 41...60 : decimalTextR = "1/2"
    case 61...72 : decimalTextR = "2/3"
    case 73...79 : decimalTextR = "3/4"
    case 90...110 : decimalTextR = "1"
    default : decimalTextR = ""
    }

    cupsWater.text = "\(resultRiceInteger) and \(decimalTextR)" // UILabel displayed on my stored board.

    let cupsRiceText = resultRiceConversion.value > 1 ? "cups" : "cup"
    if resultRiceInteger > 0 {
        cupsRice.text = "\(resultRiceInteger) \(decimalTextR) \(cupsRiceText)" // UILabel displayed on my stored board.
    } else {
        cupsRice.text = "\(decimalTextR) \(cupsRiceText)"
    }`