logo elektroda
logo elektroda
X
logo elektroda

ESP8266/ESP32: DOUBLE to INT conversion - how to write the first number after the decimal point?

powerT 603 3
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 19501334
    powerT
    Level 9  
    how to solve this problem?

    suppose
    DOUBLE number = 23.4;

    int digit1 = int(t) / 10; // takes the value 2 (it is OK)
    int digit2 = int(t) % 10; // assumes value 3 (it is OK)

    double temp = int(number) - number; // temp takes the value -0.4 (it is OK)
    temp = abs(temp); // temp takes the value 0.4 (it is OK)

    int W = temp * 10; // 0.4 * 10

    Serial.println(W); is 5 !!! (why is it always 1 more) ????

    How to get around this, in total it needs to write the first number after the decimal point to the INT variable. Any other solution ?
  • ADVERTISEMENT
  • #2 19501917
    khoam
    Level 42  
    What is the result of the following command?
    Code: C / C++
    Log in, to see the code
    .
  • ADVERTISEMENT
  • #3 19506446
    powerT
    Level 9  
    khoam wrote:
    What is the result of the following command?
    Code: C / C++
    Log in, to see the code
    .

    if temp is 0.4 then the result is 3.0000 at Serial.println(temp * 10, 5)

    it still rounds strangely.

    even so
    double t = 23.4;
    double partTotal;

    int digit3 = modf(t, & integer part)*10; // result 3 !!! should be 4
    int digit1 = int(partCalculus) / 10; // result 2 (OK)
    int digit2 = int(integer part) % 10; // result 3 (OK)

    ---- ROZWIAZANE --------------------------------------------------------------------------------
    This is how I finally managed to get the correct value, only that overall the method of
    calculations almost the same - it's a conundrum yet....

    double t = 23.4;
    int digit3 = (t*10); // gets 234
    Serial.println(digit3); // gets 4
  • #4 19506613
    khoam
    Level 42  
    powerT wrote:
    if temp is 0.4 then the result is 3.0000 at Serial.println(temp * 10, 5)
    .
    On my ESP32 it is correct. After running the code:
    Code: C / C++
    Log in, to see the code
    .
    I get a result of 4.00000
ADVERTISEMENT