简体   繁体   中英

Round Double value in objective c

How to round double value in objective c if the value is 1.66 it show value to 1.55 there is missing a point value which makes a difference if the calculations are higher?

self.priceLabel.text = [NSString stringWithFormat:@"%0.2f",totalPrice];

i have used multiple others things including formatter but this issue remain same

calculations from calculator show value like 293.76 but from this way it show value 293.75 i need the value to be 293.76

Here is something to illustrate.

All looks good?? What is the problem?

#import <Foundation/Foundation.h>

NSString * round02( double val )
{
    return [NSString stringWithFormat:@"%.2f", val];
}

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        // insert code here...
        NSLog(@"Hello, World!");

        double x = 0;

        while ( x < 3 )
        {
            x += 0.001;
            NSLog ( @"Have %f becomes %@ and %@", x, round02( x ), round02( -x ) );
        }
    }

    return 0;
}

time passes

In fact, I can see lots of trouble. Not sure if this is what is bugging you, but eg in the output it shows

2021-03-04 12:37:13.116147+0200 Rounding[15709:202740] Have 2.723000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116210+0200 Rounding[15709:202740] Have 2.724000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116316+0200 Rounding[15709:202740] Have 2.725000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116383+0200 Rounding[15709:202740] Have 2.726000 becomes 2.73 and -2.73

The last 2.72 should have been a 2.73 but, again this is a complex issue. Here is a simple way to solve it - add a tolerance as in the example below.

NSString * round02( double val )
{
    double tol = 0.0005;

    if ( val >= 0 )
    {
        return [NSString stringWithFormat:@"%.2f", val + tol];
    }
    else
    {
        return [NSString stringWithFormat:@"%.2f", val - tol];
    }
}

This does not directly address the complexities and there are cases where this will fail as well, but it will go a long way to getting the job done, eg now the output reads

2021-03-04 12:40:11.274826+0200 Rounding[15727:204617] Have 2.723000 becomes 2.72 and -2.72
2021-03-04 12:40:11.274941+0200 Rounding[15727:204617] Have 2.724000 becomes 2.72 and -2.72
2021-03-04 12:40:11.275016+0200 Rounding[15727:204617] Have 2.725000 becomes 2.73 and -2.73
2021-03-04 12:40:11.275096+0200 Rounding[15727:204617] Have 2.726000 becomes 2.73 and -2.73

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM