cool hit counter Objective-CFloat to NSString decimal inaccurate solution_Intefrankly

Objective-CFloat to NSString decimal inaccurate solution


It is common to encounter problems in development where Float types are inaccurate when converted to NSString types

float a = 0.96;
NSString *str = [NSString stringWithFormat:@"%.1f",a];
NSLog(@"%@",str);

printable

2018-05-25 16:24:14.457366+0800 Test[19641:4237944] 1.0

What we want is an output of 0.9

What about this kind of problem? An NSString Category can be written to handle

#import "NSString+Precision.h"

@implementation NSString (Precision)

/**
  Float type to string to get N decimal places
 
  @param value The Value to be converted
  @param position Decimal places
  @return Converted string
 */
+ (NSString *)decimalNumberWithFloat:(float)value position:(int)position
{
    NSString *doubleString        = [NSString stringWithFormat:@"%lf", value];
    NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];
    NSString *decStr = [decNumber stringValue];
    
    // gain"." in the string where theRange
    NSRange range = [decStr rangeOfString:@"."];
     // Handle the case of integers without decimal points (add two zeros after the decimal point to facilitate conversion to amounts)
    if (range.length == 0) {
        decStr = [NSString stringWithFormat:@"%@.00",decStr];
    }
    
    range = [decStr rangeOfString:@"."];
     // Maximum interception range
    NSInteger maxCutRange = decStr.length - range.location - 1;
     // whether the maximum interception range is exceeded
    if (position <= maxCutRange) {
        decStr = [decStr substringWithRange:NSMakeRange(0, range.length + position + range.location)];
    }
    else{
         // Out of range at maximum
        decStr = [decStr substringWithRange:NSMakeRange(0, range.length + maxCutRange + range.location)];
    }
    
    return decStr;
}

@end
NSLog(@"-----------%@",[self decimalNumberWithFloat:0.96 position:1]);

 exports
2018-05-25 16:27:53.547775+0800 DD[19782:4242695] -----------0.9

Recommended>>
1、scrapy common commands
2、Is selling strawberries the same as selling airline tickets
3、Drip data 400 cities travel nights Beijing has the highest percentage of people going home after 2100
4、springbootsecurity integration 2
5、How exactly should Spark and RDD be understood

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号