[英]Convert a string to float in Objective C without rounding it.?
如何在不对其进行舍入的情况下将字符串转换为在Objective C中浮动。
我试着转换字符串8.56021285234;
float result=[string floatValue];
给出8.560213,舍入值。
我怎么能避免这个? 我怎么能得到确切的价值?
你不能在浮点数中输入超过7位数的精度。 你需要一个更精确的类型,比如double,请看这里:
问题是你正在使用浮动。 浮动通常最多只能容纳7位数。 双人可以容纳更多数字。 浮点数为32位,而double为64位,因此精度为“double”。 解决问题的一个简单方法是:
double result = [string doubleValue];
记录时,请务必使用NSLog(@"%.12f",result);
显示整个双精度%%f默认只有6位小数精度。
尝试double而不是float:
NSString *val = @"8.56021285234";
double num = [val doubleValue];
NSLog(@"Number ==> %f",num);
如果你想转换它使用
double result = [string doubleValue];
要显示它,请使用%.10f指定小数位:
NSLog(@"%.10f", result);
NSString *value = @"8.44654656565";
double dblValue = [value doubleValue];
NSLog(@"%.10f",dblValue);
double变量具有您需要的所有信息,然后您将其格式化为文本系统可以显示不存储在double变量中的整个数字
Sabareesh代码:
NSString *value = @"8.44654656565";
double dblValue = [value doubleValue];
NSLog(@"%.12f",dblValue);
这里dblValue在内存中有你想要的所有数字,你可以根据需要使用它
这里的NSLog可以证明你有足够的数据 - 只是因为NSLog输出它
请尝试NSDecimal Number而不是[string floatValue];
NSDecimalNumber *price1 = [NSDecimalNumber decimalNumberWithString:@"15.99"];
NSDecimalNumber *price2 = [NSDecimalNumber decimalNumberWithString:@"29.99"];
NSDecimalNumber *coupon = [NSDecimalNumber decimalNumberWithString:@"5.00"];
NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@".90"];
NSDecimalNumber *numProducts = [NSDecimalNumber decimalNumberWithString:@"2.0"];
NSDecimalNumber *subtotal = [price1 decimalNumberByAdding:price2];
NSDecimalNumber *afterCoupon = [subtotal decimalNumberBySubtracting:coupon];
NSDecimalNumber *afterDiscount = [afterCoupon decimalNumberByMultiplyingBy:discount];
NSDecimalNumber *average = [afterDiscount decimalNumberByDividingBy:numProducts];
NSDecimalNumber *averageSquared = [average decimalNumberByRaisingToPower:2];
NSLog(@"Subtotal: %@", subtotal); // 45.98
NSLog(@"After coupon: %@", afterCoupon); // 40.98
NSLog((@"After discount: %@"), afterDiscount); // 36.882
NSLog(@"Average price per product: %@", average); // 18.441
NSLog(@"Average price squared: %@", averageSquared); // 340.070481
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.