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?
我有一个浮点数25.00,但当我在屏幕上打印时,它是25。0000000。如何只用两个小数来显示值?
13 个解决方案
#1
621
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 0
s.
%。02f告诉格式化程序您将格式化一个浮点数(%f),并且应该将其四舍五入到两个位置,并且应该用0填充。
E.g.:
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
#2
180
Here are few corrections-
这里有一些修正
//for 3145.559706
Swift 3
斯威夫特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
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...
等等……
#3
20
You can also try using NSNumberFormatter:
你也可以尝试使用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.
你可能也需要设置消极的格式,但我认为它足够聪明的解决它。
#4
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:
在Swift语言中,如果你想显示你需要用这种方式使用它。在UITextView中分配双值,例如:
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:
如果您想要像objective-c那样使用NSLog()显示日志,那么在Swift语言中,您可以这样做:
println(NSString(format:"%.2f", result))
#5
7
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
#6
3
IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:
在objective-c中,如果你处理的是常规的char数组(而不是指向NSString的指针),你也可以使用:
printf("%.02f", your_float_var);
OTOH, if what you want is to store that value on a char array you could use:
OTOH,如果你想要将这个值存储在一个char数组中,你可以使用:
sprintf(your_char_ptr, "%.02f", your_float_var);
#7
2
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:
所有答案的问题是,乘然后除会导致精度问题,因为你使用除法。我很久以前就从PDP8上的编程中学到了这一点。解决这个问题的方法是:
return roundf(number * 100) * .01;
Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.
因此,15.6578的回报率只有15.66,而不是15.6578999或类似的东西。
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.
你想要的精确程度取决于你自己。不要把乘积除以小数的等价物。不需要有趣的字符串转换。
#8
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
在目标-c中,u要在2个十进制数中显示浮点数,然后传递参数,指示u要显示多少个十进制数。g 0.02f打印25.00 0.002f打印25.000
#9
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
= > 2.3453
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];
=> 2
= > 2
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];
=> 2.35 (round up)
= > 2.35(四舍五入)
#10
1
Another method for Swift (without using NSString):
Swift的另一种方法(不使用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
本解决方案不适用CGFloat类型,只适用于Float & Double
#11
1
Use NSNumberFormatter
with maximumFractionDigits
as below:
使用NSNumberFormatter,其最大值如下:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);
And you will get 12.35
得到12。35
#12
0
If you need to float value as well:
如果你也需要浮动值:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
#13
0
lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];
#1
621
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 0
s.
%。02f告诉格式化程序您将格式化一个浮点数(%f),并且应该将其四舍五入到两个位置,并且应该用0填充。
E.g.:
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
#2
180
Here are few corrections-
这里有一些修正
//for 3145.559706
Swift 3
斯威夫特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
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...
等等……
#3
20
You can also try using NSNumberFormatter:
你也可以尝试使用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.
你可能也需要设置消极的格式,但我认为它足够聪明的解决它。
#4
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:
在Swift语言中,如果你想显示你需要用这种方式使用它。在UITextView中分配双值,例如:
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:
如果您想要像objective-c那样使用NSLog()显示日志,那么在Swift语言中,您可以这样做:
println(NSString(format:"%.2f", result))
#5
7
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
#6
3
IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:
在objective-c中,如果你处理的是常规的char数组(而不是指向NSString的指针),你也可以使用:
printf("%.02f", your_float_var);
OTOH, if what you want is to store that value on a char array you could use:
OTOH,如果你想要将这个值存储在一个char数组中,你可以使用:
sprintf(your_char_ptr, "%.02f", your_float_var);
#7
2
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:
所有答案的问题是,乘然后除会导致精度问题,因为你使用除法。我很久以前就从PDP8上的编程中学到了这一点。解决这个问题的方法是:
return roundf(number * 100) * .01;
Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.
因此,15.6578的回报率只有15.66,而不是15.6578999或类似的东西。
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.
你想要的精确程度取决于你自己。不要把乘积除以小数的等价物。不需要有趣的字符串转换。
#8
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
在目标-c中,u要在2个十进制数中显示浮点数,然后传递参数,指示u要显示多少个十进制数。g 0.02f打印25.00 0.002f打印25.000
#9
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
= > 2.3453
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];
=> 2
= > 2
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];
=> 2.35 (round up)
= > 2.35(四舍五入)
#10
1
Another method for Swift (without using NSString):
Swift的另一种方法(不使用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
本解决方案不适用CGFloat类型,只适用于Float & Double
#11
1
Use NSNumberFormatter
with maximumFractionDigits
as below:
使用NSNumberFormatter,其最大值如下:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);
And you will get 12.35
得到12。35
#12
0
If you need to float value as well:
如果你也需要浮动值:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
#13
0
lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];