objective c - Make a float only show two decimal places

ID : 10315

viewed : 28

Tags : objective-cformattingfloating-point

Top 5 Answer for objective c - Make a float only show two decimal places

vote vote


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.


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.


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


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" 


@"%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...

vote vote


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.

vote vote


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


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


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

Top 3 video Explaining objective c - Make a float only show two decimal places