[objective-c] Make a float only show two decimal places

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?

This question is related to objective-c formatting floating-point

The answer is


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


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

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

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

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


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.


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


If you need to float value as well:

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

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)


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


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.


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

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results