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
EasyTurn a temperature into Fahrenheit:
- make
float celsius = 21.5; - work out
celsius * 9 / 5 + 32into afloatcalledfahrenheit - print
fahrenheitwith 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() {
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in First Circuits
3Math on the Board
Named ConstantsArithmetic OperatorsInteger DivisionDecimals with floatA Blink That Speeds UpPractice on your own: Arduino playground