Arduino prints float/double variable with decimal places?

How to print float/double variable with two or three decimal places to Serial Monitor on Arduino?

Answer

The below Arduino code print float and double number to Serial Monitor with one, two, three and four decimal places.

void setup() { Serial.begin(9600); float fNumber = 0.123456; double dNumber = 9.123456; Serial.println(fNumber, 1); // print float number with one decimal place Serial.println(fNumber, 2); // print float number with two decimal place Serial.println(fNumber, 3); // print float number with three decimal place Serial.println(fNumber, 4); // print float number with four decimal place Serial.println(dNumber, 1); // print double number with one decimal place Serial.println(dNumber, 2); // print double number with two decimal place Serial.println(dNumber, 3); // print double number with three decimal place Serial.println(dNumber, 4); // print double number with four decimal place } void loop() { }

The result on Serial Monitor

COM6
Send
0.1 0.12 0.123 0.1235 9.1 9.12 9.123 9.1235
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Please note that the number will be rounded before being printed. As you can see on Serial Monitor, when printing 0.123456 with four decimal places, it is rounded to 0.1235

Buy Arduino

1 × Arduino UNO Buy on Amazon
1 × USB 2.0 cable type A/B Buy on Amazon
1 × Jumper Wires Buy on Amazon
Please note: These are affiliate links. If you buy the components through these links, We may get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES