how to approximate values

edited March 2015 in Programming Questions

Hi, I have float values let's say range (-100.0, 300.0). I cast to int to do a first approximation but then what if I want to say that every value ranging from 50 to 55 must be equal to 50 and from 55 to 60 equal to 60? As I have to do this for all the range (400 int values) is there an easy way to do this other than check for every number if is is the first 5 digits or the second 5?

some examples 44 = 40 256 = 257 122 = 120 -43 = -40

thanks

Answers

  • edited March 2015 Answer ✓
    // forum.processing.org/two/discussion/9850/how-to-approximate-values
    
    static final float OFFSET = 1e-3;
    
    static final float round10(float f, float c) {
      return round(f/10.0 - c) * 10.0;
    }
    
    void setup() {
      println(round10(55.0, OFFSET));
      println(round10(55.5, OFFSET));
      println(round10(60.0, OFFSET));
      println(round10(-43.0, OFFSET));
      exit();
    }
    
  • thanks!

Sign In or Register to comment.