objective-c 使浮点数只显示两位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:09:07  来源:igfitidea点击:

Make a float only show two decimal places

objective-cformattingfloating-point

提问by Andrew Grant

I have the value 25.00in 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在 a 中有值float,但是当我在屏幕上打印它时它是25.0000000.
如何显示只有两位小数的值?

回答by Andrew Grant

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

%.02ftells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

%.02f告诉格式化程序您将格式化一个浮点数 ( %f) 并且应该四舍五入到两个位置,并且应该用0s填充。

E.g.:

例如:

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

回答by Vaibhav Saran

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

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

等等...

回答by Rick

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.

您可能还需要设置否定格式,但我认为它足够聪明,可以弄清楚。

回答by codingrhythm

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

回答by imti

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 中分配 double 值,例如:

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() 在 LOG 中显示,那么在 Swift 语言中你可以这样做:

println(NSString(format:"%.2f", result))

回答by ztalbot

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.

您想要的精确度由您决定。只是不要除以乘积,乘以十进制等价物。不需要有趣的字符串转换。

回答by Pablo Santa Cruz

IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:

在objective-c 中,如果您正在处理常规字符数组(而不是指向 NSString 的指针),您还可以使用:

printf("%.02f", your_float_var);

OTOH, if what you want is to store that value on a char array you could use:

OTOH,如果您想要将该值存储在一个字符数组上,您可以使用:

sprintf(your_char_ptr, "%.02f", your_float_var);

回答by shaunak

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 中,您想以 2 个十进制数显示浮点值,然后传递指示您想显示多少个小数点的参数,例如 0.02f 将打印 25.00 0.002f 将打印 25.000

回答by Ryan

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(向上取整)

回答by Aks

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 CGFloattype only tested with Float& Double

PS 此解决方案不适用于CGFloat类型,仅使用Float&进行测试Double