GitHub

Practice

Practice - 004

A program to read floating point number and print it in exponent notation

use std::io::{stdin,stdout,Write};
fn main() {
practice4()
}
fn practice4() {
let mut s=String::new();
print!("Please enter some text: ");
let _=stdout().flush();
stdin().read_line(&mut s).expect("failed to read from stdin");
if let Some('\n')=s.chars().next_back() {
s.pop();
}
if let Some('\r')=s.chars().next_back() {
s.pop();
}
println!("You typed: {}",s);
let trimmed = s.trim();
let (is_float, float) = match trimmed.parse::<f32>() {
Ok(f) => (true, f),
Err(..) => (false, 0.0),
};
if !is_float {
println!("This is not an float: {}", trimmed);
return;
}
println!("Floating point: {}", float);
println!("Lower Exp: {:e}", float);
println!("Upper Exp: {:E}", float);
}

Result

Please enter some text: 15
You typed: 15
Floating point: 15
Lower Exp: 1.5e1
Upper Exp: 1.5E1
Please enter some text: 13.0_f32
You typed: 13.0_f32
This is not an float: 13.0_f32
Previous
Practice - 003