浮点到字符串(删除尾随零)[重复]

时间:2022-05-10 22:23:31

This question already has an answer here:

这个问题在这里已有答案:

Can anyone help me with converting float to string?

任何人都可以帮我转换浮点数到字符串?

if I use [NSString stringWithFormat:@"%f", f] I will get something like: 1.0300000 1.0000000 1.0471000

如果我使用[NSString stringWithFormat:@“%f”,f]我会得到类似的东西:1.0300000 1.0000000 1.0471000

if I use [NSString stringWithFormat:@"%.2f", f] I will get rounded values like: 1.03 1.00 1.05

如果我使用[NSString stringWithFormat:@“%。2f”,f]我会得到舍入值,如:1.03 1.00 1.05

but I need 1.03 1 1.0471

但我需要1.03 1 1.0471

please help!

2 个解决方案

#1


1  

try this code for your project

为您的项目尝试此代码

- (NSString *) floatToString:(float) val {
    NSString *ret = [NSString stringWithFormat:@\"%.5f\", val];
    unichar c = [ret characterAtIndex:[ret length] - 1];
    while (c == 48 || c == 46) { // 0 or .
        ret = [ret substringToIndex:[ret length] - 1];
        c = [ret characterAtIndex:[ret length] - 1];
    }
    return ret;
}

#1


1  

try this code for your project

为您的项目尝试此代码

- (NSString *) floatToString:(float) val {
    NSString *ret = [NSString stringWithFormat:@\"%.5f\", val];
    unichar c = [ret characterAtIndex:[ret length] - 1];
    while (c == 48 || c == 46) { // 0 or .
        ret = [ret substringToIndex:[ret length] - 1];
        c = [ret characterAtIndex:[ret length] - 1];
    }
    return ret;
}

#2