Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Increment / Decrement Decimals

lukeirvinlukeirvin Posts: 388Registered Users @ @
What's the proper way to increment or decrement a float?

For example... 1.0 to 1.1 or 2.3 to 2.2

Thanks!

Replies

  • chuckc192000chuckc192000 FloridaPosts: 391New Users @ @
    x += 0.1;
  • arunkumar164arunkumar164 LondonPosts: 3New Users Noob
    for simple calculations, you can use assignment operators like += & -=.
    But if you are trying in a loop then suggest to use double or NSDecimalNumber, which may more precision compared to float variables.
  • marktwomarktwo Posts: 57New Users @
    Floating-point arithmetic (addition, subtraction, etc...) is imprecise:
    1.0 + 0.1 does not equal 1.1, but 1.09999999999999999.

    The same goes for doubles too.
    If you need exact values, use integers.
  • Duncan CDuncan C Posts: 9,114Tutorial Authors, Registered Users @ @ @ @ @ @ @
    marktwo wrote: »
    Floating-point arithmetic (addition, subtraction, etc...) is imprecise:
    1.0 + 0.1 does not equal 1.1, but 1.09999999999999999.

    The same goes for doubles too.
    If you need exact values, use integers.

    Indeed, if you're always dealing in exact 10ths, use integers and display them by dividing by 10, printing a period, and displaying the number modulo 10.

    Something like this
    int tenths = 724; //Represents 72.4
    
    
    - (NSString *) stringFromTenths: (int) tenthsValue;
    {
      return [NSString stringWithFormat: @"%d.%d", tenthsValue/10, tenthsValue %10];
    }
    
    
    NSLog(@"tenthsValue = %@", [self stringFromTenths: tenths]); 
    
    Regards,
    Duncan C
    WareTo

    widehead.gif
    Animated GIF created with Face Dancer, available for free in the app store.

    I'm available for one-on-one help at CodeMentor
Sign In or Register to comment.