double datatype+iphone
i have a one application i know The range of a double is **1.7E +/- 308 (15 digits).**
but in my application i have to devide text box 's value to 100.0 my code is
double value=[strPrice doubleValue]/100.0;
NSString *stramoount=[@"" stringByAppendingFormat:@"%0.2f",value ];
when i devide 34901234566781212 by 100 it give me 3490123开发者_JS百科45667812.12 but when i type 349012345667812124 and devide by 100 it give me by 100 it give me 3490123456678121.00 which is wrong whether i change datatype or how can i change my code
The number 349012345667812124 has 18 decimal digits. the double
format only provides slightly less than 16 decimal digits of precision (the actual number is not an integer because the format's binary digits do not correspont directly to decimal ones). Thus it is completely expected that the last 2 or 3 digits cannot be represented accurately, and it already happens when the literal "349012345667812124" is parsed to the double
format, before any calculations happen.
The fact that you get the expected result with the number 34901234566781212 means nothing; it just happens to be close enough to the nearest value the double
format can represent.
To avoid this problem, use the NSDecimal
or NSDecimalNumber
types.
Use
NSDecimalNumber * dec=[[NSDecimalNumber decimalNumberWithString:value.text locale: [NSLocale currentLocale]] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100" locale:[NSLocale currentLocale]]];
NSLog(@"%@",dec);
instead of Double
精彩评论