Menu
CoddyTech

Decimals Need an f

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 3 of 85.

Whole numbers are not enough for a game: a balloon floats at 3.5, a player runs at 4.2 units a second. Numbers with a decimal point have their own type, float:

float speed = 4.2f;

Notice the f at the end. In C#, a plain 4.2 is a double, another decimal type, and Unity's positions and sizes are floats. The f tells C# the number is a float. Leave it out and Unity refuses to start the game, with this error in the Console:

error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type

It looks scary, but it only means "add the f". A whole number like 2 needs no f: it fits in a float as it is.

One more surprise: dividing two ints keeps only the whole part, so 7 / 2 is 3. Write 7 / 2f to get 3.5.

challenge icon

Challenge

Easy

Fix the balloon's script, then make it float higher and bigger.

  1. Press Play: the Console shows error CS0664 on the height line.
  2. Change that line to float height = 3.5f;.
  3. Change the size line to float size = 1.5f;. Every number with a decimal point needs its f.

Press Play: the balloon floats at 3.5, one and a half times its size. Then Check.

Try it yourself

using UnityEngine;

public class Balloon : MonoBehaviour
{
    void Start()
    {
        float height = 2.5;
        float size = 1;

        transform.position = new Vector3(0, height, 0);
        transform.localScale = new Vector3(size, size, size);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground