I need to do a sort of round, for example:
0.1 should become 0.0
0.2 => 0.0
0.3 => 0.5
0.4 => 0.5
0.5 => 0.5
0.6 => 0.5
0.7 => 0.5
0.8 => 1.0
0.9 => 1.0
1.0 => 1.0
I looked around on ceil() and floor() but they dont offer what I am looking for.
Any suggestions??
untested code, but the idea works:
semi_rounded = round(var*2.0)/2.0;
you may need to rescale the value to an integer and then back
[quote="chris_abc, post:2, topic:855266"]
semi_rounded = round(var*2.0)/2.0;
[/quote]I did a quick test but the result is always .5
Serial.begin(9600);
for (float X = 0; X <= 1; X = X + .1) {
Serial.print( round(.3 * 2.0) / 2.0);
}
}// end setup
Well yes, you input 0.3 in the loop every time. This should work:
Serial.begin(9600);
for (float X = 0; X <= 1; X = X + .1) {
Serial.print( round(X* 2.0) / 2.0);
}
}// end setup
I haven't tested it yet though.
When/if you do, test negative values too.
a7
Going in steps of 0.01 from -2 to +2:
-2.00 -2.00
...
-1.75 -2.00
-1.74 -1.50
...
-1.25 -1.50
-1.24 -1.00
...
-0.75 -1.00
-0.74 -0.50
...
-0.25 -0.50
-0.24 0.00
...
0.25 0.00
0.26 0.50
...
0.75 0.50
0.76 1.00
...
1.25 1.00
1.26 1.50
...
1.75 1.50
1.76 2.00
...
2.00 2.00
It works, many thanks. Here's my test sketch:
#define myround(R) round(R * 2.0) / 2.0
void setup() {
Serial.begin(9600);
/*********************************************************************************************
The total amount to be paid ending in .01 € or .02 € is rounded to the lower .00 €.
The total amount to be paid ending in .03 € or .04 € is rounded up to the higher .05 €.
The total amount to be paid ending in .06 € or .07 € is rounded down to the lower .05 €.
The total amount to be paid that ends in. 08 € or. 09 € is rounded up to the higher, 00 €.
*********************************************************************************************/
for (float X = 123.0; X <= 124.0; X = X + .1) {
Serial << myround(X) << endl;
}
}// end setup
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.