title: Converting Double to NSNumber in Swift Loses Accuracy
body: <p>For some reason, certain Doubles in my Swift app are giving me trouble when converting to NSNumber, while some are not. My app needs to convert doubles with 2 decimal places (prices) to NSNumbers so they can be stored and retrieved using Core Data. For example, a few particular prices such as 79.99 would evaluate to 99.98999999999999 unless specifically formatted using NSNumber's doubleValue method. </p>
  
  <p>Here selectedWarranty.price = 79.99 as shown in debugger</p>
  
  <pre><code>// item.price: NSNumber?       
  // selectedWarranty.price: Double?  
  
  item.price = NSNumber(double: selectedWarranty.price!)
  </code></pre>
  
  <p>I programmed some print statements to show how the conversion works out</p>
  
  <pre><code>Original double: 79.99
  Converted to NSNumber: 79.98999999999999
  .doubleValue Representation: 79.99
  </code></pre>
  
  <p>Can somebody explain if there is a reason why the initializer cannot surely keep 2 decimal places for every number? I would really like to store the prices in Core Data like they should be. Formatting every time it is displayed doesn't sound very convenient.  </p>
  
  <p><strong>UPDATE</strong>:
  Converted Core Data object to type NSDecimalNumber through data model, 79.99 and 99.99 no longer a problem, but now more manageable issue with different numbers...</p>
  
  <pre><code>Original double: 39.99
  Converted to NSDecimalNumber: 39.99000000000001024
  </code></pre>