Correcting floating point numbers

后端 未结 2 1328
予麋鹿
予麋鹿 2020-12-01 22:12

I am wondering if there is a way that you can easily and safely correct floating point numbers.

For example,

When entered: \" 32 + 32.1 \" Result: \"64.09999

相关标签:
2条回答
  • 2020-12-01 22:46

    Floating point numbers do not represent specific numbers very well. Using double's will make this happen less often but you will still have the problem. For a technical description of how floating point numbers are stored (and why we have this problem in the first place) see this wikipedia article: IEEE 754-1985. (Basically, floats are stored as a binary representation of the value and only have so many bits to use, so they quickly run out and have to round to the nearest value that they are capable of representing.)

    Typically you don't worry about the +/- .0000001 and just format them when you want to display them to the user with the appropriate number of decimal points and it will get rounded. Internally it doesn't really matter how it is stored though.

    For instance, if you want to display the "result" you can do something like this:

    float myFloat = 32 + 32.1;
    NSString *result = [NSString stringWithFormat:%@"%.2f", myFloat];
    // result will contain 64.10
    

    If you don't want a fixed number of decimal points, you can also use the float to string conversion capability of NSNumber:

    float myFloat = 32 + 32.1;
    NSNumber *myNumber = [NSNumber numberWithFloat:myFloat];
    NSString *result = [myNumber stringValue];
    // result will contain 64.1
    

    NSDecimalNumber will take care of all of this for you, but it a little more involved and involves more overhead but here's an example to get you started:

    NSDecimalNumber *num1   = [NSDecimalNumber decimalNumberWithString:@"32"];
    NSDecimalNumber *num2   = [NSDecimalNumber decimalNumberWithString:@"32.1"];
    // Or since you use exponents:  
    // NSDecimalNumber *num2   = [NSDecimalNumber decimalNumberWithMantissa:321 exponent:-1 isNegative:NO];
    
    NSDecimalNumber *myNumber = [num1 decimalNumberByAdding:num2];
    NSString *result = [myNumber stringValue];
    // result will contain 64.1
    
    0 讨论(0)
  • 2020-12-01 22:58

    You can't "correct" a floating point number because floating point numbers simply cannot represent the number you want.

    Floating point numbers are remarkably imprecise and, generally, shouldn't be used for anything that involves lots of calculations because the cumulative error is often catastrophically bad.

    Use a double instead. They can represent a much greater range of values and, as a result, can represent many more values quite precisely. If that isn't good enough, you'll need to move to something with more precision. Possibly NSDecimalNumber.

    0 讨论(0)
提交回复
热议问题