Menu
CoddyTech

Decimals with float

Part of the First Circuits section of Coddy's Arduino journey. Lesson 16 of 22.

An int only holds whole numbers. For a number with a fraction, use float:

float price = 2.75;

Serial.println(price) prints two digits after the point, 2.75. Give it a second number to choose how many: Serial.println(price, 3) prints 2.750.

Watch out for whole numbers inside a formula. In price * (9 / 5), the 9 / 5 is worked out first, with two whole numbers, and gives 1. Write the formula so a float is part of each division: price * 9 / 5 works left to right, and price * 9 is already a decimal number.

challenge icon

Challenge

Easy

Turn a temperature into Fahrenheit:

  • make float celsius = 21.5;
  • work out celsius * 9 / 5 + 32 into a float called fahrenheit
  • print fahrenheit with 3 digits after the point

It should show 70.700. Press Run, then Check.

Try it yourself

void setup() {
  Serial.begin(9600);
  // make celsius, work out fahrenheit, print it with 3 decimals
}

void loop() {
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in First Circuits

Practice on your own: Arduino playground