Make a float only show two decimal places

Objective CFormattingFloating Point

Objective C Problem Overview


I have the value 25.00 in a float, but when I print it on screen it is 25.0000000.
How can I display the value with only two decimal places?

Objective C Solutions


Solution 1 - Objective C

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

E.g.:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

E.g.:

%f = 25.000000
%.f = 25
%.02f = 25.00

Solution 2 - Objective C

Here are few corrections-

//for 3145.559706

Swift 3

let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to @"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to @"%.3f"

Obj-C

@"%f"    = 3145.559706
@"%.f"   = 3146
@"%.1f"  = 3145.6
@"%.2f"  = 3145.56
@"%.02f" = 3145.56 // which is equal to @"%.2f"
@"%.3f"  = 3145.560
@"%.03f" = 3145.560 // which is equal to @"%.3f"

and so on...

Solution 3 - Objective C

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

Solution 4 - Objective C

I made a swift extension based on above answers

extension Float {
    func round(decimalPlace:Int)->Float{
        let format = NSString(format: "%%.%if", decimalPlace)
        let string = NSString(format: format, self)
        return Float(atof(string.UTF8String))
    }
}

usage:

let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true

Solution 5 - Objective C

In Swift Language, if you want to show you need to use it in this way. To assign double value in UITextView, for example:

let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)

If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way:

println(NSString(format:"%.2f", result))

Solution 6 - Objective C

IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:

printf("%.02f", your_float_var);

OTOH, if what you want is to store that value on a char array you could use:

sprintf(your_char_ptr, "%.02f", your_float_var);

Solution 7 - Objective C

The problem with all the answers is that multiplying and then dividing results in precision issues because you used division. I learned this long ago from programming on a PDP8. The way to resolve this is:

return roundf(number * 100) * .01;

Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.

What level of precision you want is up to you. Just don't divide the product, multiply it by the decimal equivalent. No funny String conversion required.

Solution 8 - Objective C

in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000

Solution 9 - Objective C

Here's some methods to format dynamically according to a precision:

+ (NSNumber *)numberFromString:(NSString *)string
{
    if (string.length) {
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        return [f numberFromString:string];
    } else {
        return nil;
    }
}

+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
    NSNumber *numberValue = [self numberFromString:string];

    if (numberValue) {
        NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
        return [NSString stringWithFormat:formatString, numberValue.floatValue];
    } else {
        /* return original string */
        return string;
    }
}

e.g.

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];

=> 2.3453

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];

=> 2

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];

=> 2.35 (round up)

Solution 10 - Objective C

Another method for Swift (without using NSString):

let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %@", percentage, "%")

P.S. this solution is not working with CGFloat type only tested with Float & Double

Solution 11 - Objective C

Use NSNumberFormatter with maximumFractionDigits as below:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

And you will get 12.35

Solution 12 - Objective C

If you need to float value as well:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);

Solution 13 - Objective C

 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionronView Question on Stackoverflow
Solution 1 - Objective CAndrew GrantView Answer on Stackoverflow
Solution 2 - Objective CVaibhav SaranView Answer on Stackoverflow
Solution 3 - Objective CRickView Answer on Stackoverflow
Solution 4 - Objective CcodingrhythmView Answer on Stackoverflow
Solution 5 - Objective CimtiView Answer on Stackoverflow
Solution 6 - Objective CPablo Santa CruzView Answer on Stackoverflow
Solution 7 - Objective CztalbotView Answer on Stackoverflow
Solution 8 - Objective CshaunakView Answer on Stackoverflow
Solution 9 - Objective CRyanView Answer on Stackoverflow
Solution 10 - Objective CAksView Answer on Stackoverflow
Solution 11 - Objective CAllen HuangView Answer on Stackoverflow
Solution 12 - Objective CloretoparisiView Answer on Stackoverflow
Solution 13 - Objective CRinju JainView Answer on Stackoverflow