1

I have Double value is 7.92021 and I want to change it to 7.92 (Double type). I was try 3 methods but all not worked!

Code 1:

let d1:Double = 7.92012
let d2 = Double(String(format: ".2f", d1)) 
// the result d2 = 7.92000000000002

Code 2:

let d1:Double = 7.92012
let value = NSDecimalNumber(double: d1)
value.decimalNumberByAdding(2)
let result = value.doubleValue
// the result = 7.92000000000002

Code 3:

let d1:Double = 7.92012
let d2 = round( d1 * 100 ) / 100
// d2 = 7.92000000000002

How I make the result value is 7.92 (double type)?

Bao Tuan Diep
  • 2,221
  • 2
  • 17
  • 23
  • http://stackoverflow.com/a/26158006/4601170 – Bhavin Bhadani Jul 26 '16 at 08:08
  • The 3rd code snippet works perfectly fine. I don't see why you are facing a problem there. – Mtoklitz113 Jul 26 '16 at 08:09
  • It depends upon what you want to do this this result. If the intent is merely to show it in the UI, then convert to a string with `NSNumberFormatter` (which is like `String(format:)`, but is localized). If you plan on doing arithmetic with it later, use `NSDecimalNumber`, not `Double`. – Rob Jul 26 '16 at 08:09
  • 1
    Understand the difference between a decimal and a string. Only a string can have a limited number of decimal digits. – Sulthan Jul 26 '16 at 08:10
  • @Sulthan - Strings aren't the _only_ way to have limited decimal points. This is what `NSDecimalNumber` is designed to solve. But, yes, in general, if merely showing the result in the UI, then a string representation is often the easiest solution. – Rob Jul 26 '16 at 08:20
  • @Rob Every decimal number, even `NSDecimalNumber` still has fractional digits. You can make them zero by rounding but you can't make them go away. The string conversion is the one that removes zero fractional digits. – Sulthan Jul 26 '16 at 08:22
  • @Sulthan I think 'NSDecimalNumber' designed to solve limited number of decimal. But I just want a double value because a string not for the calculation. – Bao Tuan Diep Jul 26 '16 at 08:28
  • @BaoTuanDiep: A binary floating point number **CANNOT** represent the number `7.92` exactly. A must-read is http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. – Martin R Jul 26 '16 at 08:31
  • @MartinR: Ok I see. So what did NSDecimalNumber made? – Bao Tuan Diep Jul 26 '16 at 08:39
  • @Sulthan - `NSDecimalNumber` is not a binary floating point number. It consists of an integer mantissa and integer exponent. – Rob Jul 26 '16 at 08:41

0 Answers0