3 Replies
      Latest reply: Oct 11, 2016 11:01 AM by T P RSS
      T P Level 1 Level 1 (0 points)

        HELP Wanted, please.


        I'm trying, with no luck, to convert a double (inches) into a string, e.g. 14.125 to 14 1/8, 0.875 to 7/8.  Because of edits, I know that the fraction will always be 0 or a multiple of 1/8" (.125).  That is a range of 0.0 to 0.875 for the fractional part of the double.


        In Windows Visual Studio languages, this is a fairly simple task.  Since I'm trying to learn Xcode and Swift 3, I can't find documentation, that I recognize, which will give me clues on how to accomplish this.


        Any thoughts or ideas will be greatly appreciated!



        • Re: How to parse a string for "." and get its index position?
          ahltorp Level 3 Level 3 (410 points)

          How are you doing it in Visual Studio? It probably is very close to the code in Swift. Here is a crude example:


              let i = floor(value)
              let f = value - i
              let s = "\(Int(i)) \(Int(rint(f*8)))/8"


          Did you also want the other question answered: "How to parse a string for "." and get its index position?"?

            • Re: How to parse a string for "." and get its index position?
              eskimo Apple Staff Apple Staff (6,075 points)

              ahltorp, Rather than relying on old school C API for this (rint), you might want to familiarise yourself with Swift 3’s new FloatingPoint protocol (SE-0067), which has a bunch of neat-o rounding support, like:

              print(2.1.rounded())                // 2.0
              print(1.9.rounded())                // 2.0
              print(1.5.rounded())                // 2.0
              print(-1.5.rounded())              // -2.0
              print(1.5.rounded(.towardZero))    // 1.0
              print(-1.5.rounded(.towardZero))    // -1.0

              @Terry, if you plan to display this string to the user, you should use NumberFormatter to render number values rather than string interpolation.  This will do the right thing regardless of the user’s locale.

              Hmmm, then again, if you’re working in eighths of an inch you probably only have one locale you need to work about (-;

              Share and Enjoy

              Quinn “The Eskimo!”
              Apple Developer Relations, Developer Technical Support, Core OS/Hardware
              let myEmail = "eskimo" + "1" + "@apple.com"