I have an oled display which can only display 4 digits + decimal point. I need a way to format the number into 4 significant figures; Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.

Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

  • printf on AVR doesn't support float formatting without some tweaking in configuration files of the builder.
    – Juraj
    Commented Feb 26, 2019 at 14:27

1 Answer 1


Normally sprintf() would be the solution - however the sprintf() in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use dtostrf() to get the job done:

dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via String (although I would never recommend using String for anything, ever):

String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.
  • Is the String class in the Arduino library reallly that bad?
    – Duncan C
    Commented Feb 26, 2019 at 16:22
  • 1
    Indeed it is. It uses dynamic allocation for the internal data storage, and that is a terrible idea when you only have 2k.
    – Majenko
    Commented Feb 26, 2019 at 16:28
  • How about for stack-allocated String objects? Won't they get freed on return, so avoid fragmentation (Obviously unless you allocate other longer-lived objects while in the same call chain.)
    – Duncan C
    Commented Feb 26, 2019 at 16:32
  • @DuncanC what is a stack-allocated arduino String? It still uses realloc and free from the heap. Allocating and releasing memory is not problem, but the fragmentation is. That is also caused by changes made to a String (the reallocate can cause fragmentation).
    – Jot
    Commented Feb 26, 2019 at 17:14
  • If you define a String as a local variable in a function, or in an expression to compose Strings from other strings, those String objects should be transient (In C++ objects assigned to local variables in functions get created on the stack, and released as soon as the function returns)
    – Duncan C
    Commented Feb 26, 2019 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.