Dual data type + iphone

I have one application that I know. The double range is **1.7E +/- 308 (15 digits).** , but in my application I need to divide the value of the text field by 100.0 , my code

 double value=[strPrice doubleValue]/100.0; NSString *stramoount=[@"" stringByAppendingFormat:@"%0.2f",value ]; 

when I divide 34901234566781212 by 100 , it gives me 349012345667812.12 , but when I type 349012345667812124 and divide by 100 , it gives me 100 , it gives me 3490123456678121.00 , which is wrong, do I change the data type or how can I change my code

+4
source share
2 answers

Use

 NSDecimalNumber * dec=[[NSDecimalNumber decimalNumberWithString:value.text locale: [NSLocale currentLocale]] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100" locale:[NSLocale currentLocale]]]; NSLog(@"%@",dec); 

instead of Double

+1
source

The number 349012345667812124 has 18 decimal digits. the double format only provides a little less than 16 decimal digits of precision (the actual number is not an integer, since the binary digits of the format do not correspond directly to decimal). Thus, it is expected that the last 2 or 3 digits cannot be represented exactly, and this already happens when the literal "349012345667812124" is parsed in double format before any calculations are made.

The fact that you get the expected result with the number 34901234566781212 does not mean anything; it is just close to the closest value that the double format can represent.

To avoid this problem, use the NSDecimal or NSDecimalNumber .

+6
source

All Articles