Menu
Coddy logo textTech

Formatted Output

Part of the Fundamentals section of Coddy's Rust journey. Lesson 36 of 75.

challenge icon

Challenge

Beginner

Modify the output so that it will always print a float value with two decimal places. To do it use the {:.2} sign:

let num = 1.5576734;
println!("This is rounded: {:.2}", num);
// Output: This is rounded: 1.56

Try it yourself

use std::io;

fn main() {
    println!("Calculator App");

    let mut input_num1 = String::new();
    let mut input_num2 = String::new();
    io::stdin().read_line(&mut input_num1).unwrap();
    io::stdin().read_line(&mut input_num2).unwrap();
    let num1: f64 = input_num1.trim().parse().unwrap();
    let num2: f64 = input_num2.trim().parse().unwrap();
    let sum = num1 + num2;
    let difference = num1 - num2;
    let product = num1 * num2;
    let quotient = num1 / num2;
    println!("Sum: {}", sum);
    println!("Difference: {}", difference);
    println!("Product: {}", product);
    println!("Quotient: {}", quotient);
}

All lessons in Fundamentals

Practice on your own: Online Rust compiler