Search code examples
arduinoarduino-esp8266

Add decimal position to long


I have a long value and I would like to convert it to a decimal of 3.

Sample values: 324 4353 53463

If a value has a length of 3, those numbers are the decimals like: 324 should be 0.324.

If it has 4 positions of more, the last 3 numbers are the decimals, example: 4353 should be 4.353 and 53463 should be 53.463.

What would be the best way to do this... Should I convert it to String and use string operations to add the . or is there an easier way to do this (doesn't seem right)?


Solution

  • I have a long value and I would like to convert it to a decimal of 3.

    Per this and OP's other notes, its appears a string or print out is desired.

    Nominally, the below will accomplishes this. Note that d will likely have a value that is only near the mathematically multiple of 0.001, but not exactly. Yet printf() will print a rounded value as desired.

    long some_long = foo();
    double d = some_long / 1000.0;
    printf("%.3f\n", d);
    

    But what happens when the values bits in long exceed the binary precision of double?

    Print in 2 parts. Handling negative values is tricky: be sure to print the sign and use the absolute values of the most and lesser part and print leading zeros.

    long some_long = foo();
    long most = some_long / 1000;
    long least = some_long % 1000;
    printf("%s%ld.%03ld\n", "-" + (some_long >= 0), labs(most), labs(least));
    

    [to wiki - not in it for the points]