303

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
  • var nf = NSNumberFormatter() nf.positiveFormat = "0.##" var numberAfterRound = nf.stringFromNumber(NSNumber(double: number))! – kalpeshdeo Apr 15 '15 at 21:13

13 Answers13

662

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
Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
Andrew Grant
  • 58,260
  • 22
  • 130
  • 143
  • 7
    I noticed that using %.2f actually returns 25.00 in your example and not 25. This is strange. – gotnull Jan 11 '11 at 23:32
  • 3
    The way i always understood was that the number after the decimal point said how much decimals you got. So, .2f would indeed give 25.00, and .4f would give 25.0000. – Erik S Apr 08 '11 at 07:34
  • 4
    If anyone is curious _as to how one does_ **actually get** `25`.. `@"%.f"` does the trick. What is written above, **does not**. – Alex Gray Dec 03 '11 at 19:43
  • can the integer which determines the number of decimal places be a variable? like @"%.xf" where x can be any integer? – acecapades Aug 21 '12 at 06:37
  • 4
    @acecapades, if you use `@"%.*f", decimalPlaces, number` – Jonathan. Jan 30 '13 at 22:27
  • 13
    Probably this will be a partial off-topic but I would add another format: `%03.f = 025` – SoftDesigner Jul 05 '13 at 14:47
  • %03.f gives me 025, but %03.02f gives me 25.00... there a good way to get 025.00? – redux Jul 16 '13 at 23:37
  • 1
    A reference for this would be nice. I couldn't track down this information in https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265 or in http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html which is surprising given what a simple task this is - I'd expect it to be very clearly documented in a highly visible place. Do you still recall how you first came by this knowledge? – Mark Amery Sep 01 '13 at 17:05
  • %.0f will get you no decimal places – sam_smith Sep 11 '14 at 09:19
201

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

Vaibhav Saran
  • 12,848
  • 3
  • 65
  • 75
20

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.

Rick
  • 3,298
  • 3
  • 29
  • 47
10

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
codingrhythm
  • 1,456
  • 14
  • 26
9

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))
imti
  • 1,283
  • 1
  • 11
  • 12
4

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.

malioboro
  • 3,097
  • 4
  • 35
  • 55
ztalbot
  • 119
  • 1
  • 4
3

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);
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
1

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)

Ryan
  • 5,416
  • 1
  • 39
  • 36
1

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

Aks
  • 8,181
  • 5
  • 37
  • 38
1

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

shaunak
  • 19
  • 1
1

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

Allen Huang
  • 61
  • 1
  • 5
0

If you need to float value as well:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
0
 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];
Rinju Jain
  • 1,694
  • 1
  • 14
  • 23