Feels bad man float

Hi guys;

Bad calculation this float , Are there any solution proposals?

It's not a bad calculation. It's a normal truncation. What are you trying to do?

A float on your arduino is unfortunately not super precise to represent a floating point number to arbitrary precision and will lead to disappointment... here your challenge is that an int is used to store the result and thus you are rounding down - your little math is likely generating something like 999.99999999 and then you truncate by storing in an int

If you want to round a float to the nearest whole number, just add 0.5 and cast to the appropriate integer type or use the round math.h function

aarg:
It's not a bad calculation. It's a normal truncation. What are you trying to do?

i need true calculation :slight_smile:

#include <math.h>

int result1=0;

int a=6;
float b=0.60;

void setup() {
Serial.begin(9600);

}

void loop() {
result1=((a*100)/b)+0.001;
Serial.println(result1);
delay(2000);
}

result1=((a100)/b); ------>Now false. Answer 999.
result1=((a
100)/b)+0.001; ------>Now 0.001 is true. Answer 1000.

The conversion to int truncates, it does not round.

The normal way to go would be to add 0.5 before converting.

When you store the result of a float calculation in an int, the automatic cast truncates your number (999.9999999 becomes 999). If you add a tiny bit to you math then your 999.999999. Become 1000.0009999 and is truncated down to what you want.

You just need to understand how this works. if you call the round() function that will do some work for you

thank you for all answers

There are 4 IEEE floating point operators for converting a float to an integer value:

round() - to nearest
trunc() - to the integer closer to zero
ceiling() - to the integer closer to +infinity
floor() - to the integer closer to -infinity

The default is trunc, which is what a simple cast uses.

Some language systems do "true" calculation, they are called algebra systems and exhibit no error
in representing numbers by representing numbers symbollically - this is done at a great price
computationally and equality is not, in general, tractable.

For decimal fractions you can use a decimal library - these are typically used for financial calculations
where rounding errors due to conversion between binary<->decimal are not tolerated (but rounding
errors still happen, but are defined by decimal truncation and rounding).