使浮点只显示两位小数

本文翻译自:Make a float only show two decimal places

I have the value 25.00 in a float , but when I print it on screen it is 25.0000000 . 我在float25.00的值,但是当我在屏幕上打印时它是25.0000000
How can I display the value with only two decimal places? 如何只用两位小数显示值?


#1楼

参考:https://stackoom.com/question/2Lob/使浮点只显示两位小数


#2楼

If you need to float value as well: 如果您还需要浮动值:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);

#3楼

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

eg 例如

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


#4楼

 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];

#5楼

In Swift Language, if you want to show you need to use it in this way. 在Swift语言中,如果你想表明你需要以这种方式使用它。 To assign double value in UITextView, for example: 要在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: 如果你想在LOG中显示像objective-c那样使用NSLog(),那么在Swift语言中你可以这样做:

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

#6楼

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值