1

I would like to make a string with stringWithFormat from a double value, without the unnecessary zero at the end.

Examples:

  1. [NSString stringWithFormat:@"%.8f",2.344383933];

  2. [NSString stringWithFormat:@"%.8f",2.0];

expected results:

  1. 2.344383933

  2. 2

Which is the correct format ?

Thank you.

Haroldo Gondim
  • 7,725
  • 9
  • 43
  • 62
Fab
  • 1,468
  • 1
  • 16
  • 37
  • 2
    have a look here: http://stackoverflow.com/questions/1113408/limit-a-double-to-two-decimal-places – Icky Jan 30 '11 at 14:47
  • Yes, I would suppress all the 0 after the decimal point if meaningless – Fab Jan 30 '11 at 17:17

2 Answers2

0

Use NSNumberFormatter

[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",0]]

Sample:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

NSLog(@"1: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.344383933]]);
NSLog(@"2: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.0]]);

Results:

1: 2.344383933

2: 2

Haroldo Gondim
  • 7,725
  • 9
  • 43
  • 62
  • You are using `NSNumberFormatter` really in a strange way. Why would you even use `stringWithFormat`? Why are you using `numberFromString` if your result should be a `string`? What you want to do is to set `maxFractionalDigits` to `8` and just call `stringFromNumber:`. – Sulthan Mar 18 '16 at 22:45
  • Make an answer to your suggestion to make this post even more complete. – Haroldo Gondim Mar 18 '16 at 22:49
0

There is a dedicated class for number formatting, NSNumberFormatter:

let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 8

print("\(formatter.stringFromNumber(2.344383933))")
print("\(formatter.stringFromNumber(2.0))")

NSNumberFormatter will also bring localization (decimal points, grouping separators).

Sulthan
  • 128,090
  • 22
  • 218
  • 270