Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision String Format Specifier In Swift

Tags:

swift

Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b); 

I checked the docs and the eBook but haven't been able to figure it out. Thanks!

like image 864
user3524868 Avatar asked Jun 05 '14 03:06

user3524868


People also ask

How do you specify a floating point precision in a string?

For example, if a number is 45.6789, you might only want to show two digits after the decimal place. The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point.

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

The following code:

import Foundation // required for String(format: _, _)  print(String(format: "a float number: %.2f", 1.0321)) 

will output:

a float number: 1.03 
like image 129
realityone Avatar answered Oct 12 '22 06:10

realityone