在格式化显示的浮点时,限制数字的小数和总数 [英] Limiting both the fractional and total number of digits when formatting a float for display

查看:171
本文介绍了在格式化显示的浮点时,限制数字的小数和总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要最有效地在有限宽度的区域中打印浮点值。我使用一个 NSNumberFormatter ,我设置小数点后两个数字作为默认值,这样当我有一个数字 234.25 它按原样打印: 234.25 。但是当我有 1234.25 时,我想将其打印为: 1234.3 11234.25 应该打印 11234

I need to print a float value in area of limited width most efficiently. I'm using an NSNumberFormatter, and I set two numbers after the decimal point as the default, so that when I have a number like 234.25 it is printed as is: 234.25. But when I have 1234.25 I want it to be printed as: 1234.3, and 11234.25 should be printed 11234.

我需要最多两位数字后,并且如果我在点后面有数字,则最多可以有五位数,但是如果整数部分有更多,它也应该打印超过五位数。

I need a maximum of two digits after the point, and a maximum of five digits overall if I have digits after the point, but it also should print more than five digits if the integer part has more.

我看不到能够限制 NSNumberFormatter 中的总位数。这是否意味着我应该以这种方式编写我自己的函数来格式化数字?如果是这样,那么获得数字的整数和小数部分中的数字计数的正确方法是什么?我也喜欢使用 CGFLoat ,而不是 NSNumber 来避免额外的类型转换。

I don't see ability to limit the total number of digits in NSNumberFormatter. Does this mean that I should write my own function to format numbers in this way? If so, then what is the correct way of getting the count of digits in the integer and fractional parts of a number? I would also prefer working with CGFLoat, rather than NSNumber to avoid extra type conversions.

推荐答案

这是我在我的代码中实现这一点。我不知道它的效率,我希望不错。

Here is how I implemented this in my code. I don't know how efficient it is, I hope not bad.

所以我创建一个全局NSNumberFormatter

So I create a global NSNumberFormatter

NSNumberFormatter* numFormatter; 

并将其初始化到某处:

numFormatter=[[NSNumberFormatter alloc]init];

然后我用以下函数格式化数字:

Then I format number with the following function:

- (NSString*)formatFloat:(Float32)number withOptimalDigits:(UInt8)optimalDigits maxDecimals:(UInt8)maxDecimals
{
    NSString* result;
    UInt8 intDigits=(int)log10f(number)+1;
    NSLog(@"Formatting %.5f with maxDig: %d maxDec: %d intLength: %d",number,optimalDigits,maxDecimals,intDigits);  

    numFormatter.maximumFractionDigits=maxDecimals;
    if(intDigits>=optimalDigitis-maxDecimals) {
        numFormatter.usesSignificantDigits=YES;
        numFormatter.maximumSignificantDigits=(intDigits>optimalDigits)?intDigits:optimalDigits;
    } else {
        numFormatter.usesSignificantDigits=NO;
    }
    result = [numFormatter stringFromNumber:[NSNumber numberWithFloat:number]];

    return result;
}

这篇关于在格式化显示的浮点时,限制数字的小数和总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆