0

guys, I have some very little floats and I want to round it up to first not nil value. For example:

float toRound = 0.000002125231553;
toRound = //Operations//;

toRound == 0.000002;

Have you any ideas?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
werbary
  • 1,105
  • 2
  • 14
  • 43
  • 2
    Your example rounds *down* though ? – Paul R Apr 28 '12 at 10:24
  • It should round like round function (if next number < 5 - down, else - up) – werbary Apr 28 '12 at 10:35
  • You probably need to give a couple more examples in your question as it's not really clear exactly what you are trying to achieve here - do you just want one significant digit or are you looking for a specific number of decimal places ? – Paul R Apr 28 '12 at 10:37
  • I want to round float to integer, but it shouldn't be nil. If rounded to integer value equals nil, we should look for numbers after dot. – werbary Apr 28 '12 at 10:50
  • 1
    possible duplicate of [rounding with significant digits](http://stackoverflow.com/questions/6751055/rounding-with-significant-digits) – mmmmmm Apr 28 '12 at 12:53
  • The first non-zero _integer_ value, rounding _up_ from a fraction, 0 < n < 1, is 1. Problem solved. Obviously this isn't the solution you're looking for; please try to explain more clearly. The best way to do that is to give some a variety input and output samples. – jscs Apr 28 '12 at 18:28
  • What you mean is rounding to one significant digit. It's answered here: http://stackoverflow.com/questions/6751055/rounding-with-significant-digits – Vadim Yelagin Apr 28 '12 at 12:24
  • For future readers, if you're rounding w/ floor function you can just use `%g` in your NSString – Albert Renshaw Oct 23 '19 at 03:07

1 Answers1

1

perhaps not the best approach. but it does what you want ;)

float s = 0.000322333123;
BOOL exit = 0;
NSString *x = [NSString stringWithFormat:@"%f", s];
for (int i = 0; i <= [x length]; i++) {
NSString *t = [x substringToIndex:i];

if ([t floatValue] == 0 || exit == 1) {
    ;;
}
else {
    exit = 1;
    s = [t floatValue];       
}
}

NSLog(@"round: %f", s);

Log: round: 0.0003

Quirin
  • 720
  • 5
  • 10