Andrew
Andrew

Reputation: 176

How to compare decimal values


I have a problem with comparison two decimal values.
I have a text field that contains number like 0.123456 and NSNumber that contains 0.000001.
Maximum fraction digits of both is 6. Minimum - 0
I've tried to do it like that:

NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
[decimalFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[decimalFormatter setMaximumFractionDigits:6];

double sum = [[decimalFormatter numberFromString:self.summTextField.text] doubleValue];

if (self.minSum != nil) {
    if (sum < [self.minSum doubleValue]) {
        return NO;
    }
}

But i have a problem, that sometimes 0.123456 = 0,123455999... or 0,123456000000...01 For example @0.000001 doubleValue < @0.000001 doubleValue - TRUE.


How can I compare to NSNumber with a fractional part, to be sure that it will be correct?


Thanks in advance.

Upvotes: 0

Views: 2742

Answers (6)

Ashim Dahal
Ashim Dahal

Reputation: 1147

Create extension to decimal for rounding

extension Decimal {
 func rounded(toDecimalPlace digit: Int = 2) -> Decimal {
    var initialDecimal = self
    var roundedDecimal = Decimal()
    NSDecimalRound(&roundedDecimal, &initialDecimal, digit, .plain)
    return roundedDecimal
  }
}

let value1 = Decimal(2.34999999).rounded(toDecimalPlace: 4)
let value2 = Decimal(2.34999989).rounded(toDecimalPlace: 4)
print(value1.isEqual(to: value2))

this results in TRUE

Upvotes: 3

Mohammed Raisuddin
Mohammed Raisuddin

Reputation: 992

This is how NSDecimal numbers are compared in iOS:

if ( [x compare:y] == NSOrderedSame ){
    // If x is equal to y then your code here..
}

if([x compare:y] == NSOrderedDescending){
    // If x is descendant to y then your code here..
}

if([x compare:y] == NSOrderedAscending){
    // If x is ascendant to y then your code here.. 
}

Upvotes: 1

SPA
SPA

Reputation: 1289

Use the NSDecimalNumber class - see the guide Number and Values Programming Topics

Upvotes: 0

Konstantin
Konstantin

Reputation: 156

You can round your value, if you worried about fractional part... Something like this:

-(double)RoundNormal:(double) value :(int) digit
{
    value = round(value * pow(10, digit));
    return value / pow(10, digit);
}

And then compare it.

Upvotes: 0

Joel
Joel

Reputation: 16124

This should solve it:

NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
[decimalFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[decimalFormatter setMaximumFractionDigits:6];
[decimalFormatter setMinimumFractionDigits:6];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setRoundingIncrement:[NSNumber numberWithDouble:0.000001]]

Upvotes: 0

Nicolas Manzini
Nicolas Manzini

Reputation: 8546

You can simply put the test otherwise if you do not want to bother much

if(abs(x-y) < 0.0001)

Upvotes: 0

Related Questions