Menu
CoddyTech

Decimals With toStringAsFixed

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 26 of 34.

A number with a decimal point is a double. It reads from text the same way, with double.tryParse:

double.tryParse('2.5') ?? 0   // 2.5
int.tryParse('2.5') ?? 0      // 0: not a whole number

Calculations with doubles often give long tails: 5 * 0.621371 is 3.106855, and 10 / 3 is 3.3333333333333335. To show a fixed number of decimals, use toStringAsFixed. It rounds, and gives back a string:

(10 / 3).toStringAsFixed(2)   // '3.33'
3.106855.toStringAsFixed(1)   // '3.1'

The number keyboard has no decimal point by default. TextInputType.numberWithOptions(decimal: true) adds one.

challenge icon

Challenge

Medium

The app turns kilometers into miles, but it reads only whole numbers and shows long decimals.

  • Read the field with double.tryParse, so 2.5 works, and make _km a double.
  • Give the field the number keyboard with a decimal point.
  • Show the miles with two decimals: That is 3.11 miles for 5 km.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _km = 0;

  @override
  Widget build(BuildContext context) {
    final double miles = _km * 0.621371;
    return Scaffold(
      appBar: AppBar(title: const Text('Distance')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: 'Kilometers',
                border: OutlineInputBorder(),
              ),
              onChanged: (String value) {
                setState(() {
                  _km = int.tryParse(value) ?? 0;
                });
              },
            ),
            const SizedBox(height: 24),
            Text('That is $miles miles', style: const TextStyle(fontSize: 24)),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

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

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler