0

I am using NSNumberFormatter to format numbers in my application.

I just recently discovered an issue involving two added numbers and then formatting them with the numberformatter.

The configuration for the NSNumberFormatter is as follows

    var formatter = NSNumberFormatter();
    formatter.positiveFormat = "#,###,##0.00 ¤";
    formatter.formatterBehavior = NSNumberFormatterBehavior.Behavior10_4
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle

    formatter.maximumFractionDigits = 2;
    formatter.minimumFractionDigits = 2;

    formatter.locale = NSLocale.currentLocale();

Then I have the following number

var number1: Float = 0.1;
println(formatter.stringFromNumber(number1)); // output: "0.10 €"

And this number

var number2: Float = 500000;
println(formatter.stringFromNumber(number2)); // output: "500,000.00 €"

Both outputs are correct.

Now I do this:

var combined:Float = number1 + number2;
println(formatter.stringFromNumber(combined)); // output: "500,000.09 €"

Why is the result 500,000.09 and not 500,000.10 ?

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
  • 4
    `Float` is a 32-bit floating point number and has a precision of about 6-7 decimal digits. The number `500,000.10` **cannot** be represented exactly as a `Float`. – Martin R Dec 09 '14 at 18:51
  • I just tested with 5000 instead of 500000 it works there which means you are right, thank you. If you put your comment in a beautiful answer, I can accept it! – Philipp Jahoda Dec 09 '14 at 18:56
  • Try it with `Double` which has 64bit representation. – zisoft Dec 09 '14 at 18:58
  • @PhilippJahoda: This has been answered more than once. The above referenced "duplicate" is about the C language, but the issue is exactly the same. – Martin R Dec 09 '14 at 18:59
  • Yep, I just noticed. I opened a new question because I thought (wrongly) that the issue was related to the NSNumberFormatter and not to the data type. – Philipp Jahoda Dec 09 '14 at 19:01
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Martin R Dec 09 '14 at 19:03

0 Answers0