3

How to format a decial value as follows:

/// variable
double value = 9.99999

/// conversion
NSSting* str = [NSString stringWithFormat:@"%.2f", value];

/// result
9.99

but when the value is 9.00000 it is returning 9.00

How should I format the string that it would show 9.0000 as 9 and 9.99999 as 9.99??

Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100

2 Answers2

4

You should have a look on NSNumberFormatter. I added the code in Swift but you can easily convert it to Objective-C:

let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundFloor
print("\(formatter.stringFromNumber(9.00))")

// Objective-C (Credit goes to NSNoob)

        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle: NSNumberFormatterDecimalStyle];
        formatter.minimumFractionDigits = 0;
        formatter.maximumFractionDigits = 2;
        [formatter setRoundingMode:NSNumberFormatterRoundFloor];
        NSString* formattedStr = [formatter stringFromNumber:[NSNumber numberWithFloat:9.00]];
        NSLog(@"number: %@",formattedStr);
Greg
  • 25,317
  • 6
  • 53
  • 62
  • Hi greg, seeing as you probably did not have time to re-write your answer in Objective C, I have [converted it to Obj-C](http://paste.ubuntu.com/14848971/). Please add it to your answer if you want to :) – NSNoob Feb 01 '16 at 11:48
2

According to this related question's answer, you can try doing:

// Usage for Output   1 — 1.23
[NSString stringWithFormat:@"%@ — %@", [self stringWithFloat:1], 
                                       [self stringWithFloat:1.234];

// Checks if it's an int and if not displays 2 decimals.
+ (NSString*)stringWithFloat:(CGFloat)_float
{
    NSString *format = (NSInteger)_float == _float ? @"%.0f" : @"%.2f";
    return [NSString stringWithFormat:format, _float];
}

In Swift, you can use the "%g" ("use the shortest representation") format specifier:

import UIKit

let firstFloat : Float = 1.0
let secondFloat : Float = 1.2345

var outputString = NSString(format: "first: %0.2g second: %0.2g", firstFloat, secondFloat)

print("\(outputString)")

comes back with:

"first: 1 second: 1.2"

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215