简体   繁体   中英

Objective-C: how to round of double to 2 decimal places if there is some value after decimal otherwise the value should be rounded to 0 decimal places

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 ??

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);

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM