How to remove leading zero in float number

I am looking for removing first zero in this confidence variable

use std::{io, process};
extern crate whatlang; 
use whatlang::detect; 

fn main() {
  println!("Type quit anytime you want to quit the program");
  loop {
      println!("Type something >>");
      let mut text: String = String::new();
          .read_line(&mut text)
          .expect("Failed to read the line");
      let text = text.trim();
      if text == "quit" {
      let info = detect(text).expect("Failed to detect language"); 
      let confidence = (info.confidence() * 100.0).round() / 100.0; 
      println!("Language: {}", info.lang());
      println!("Script: {}", info.script());
      println!("Confidence: {}%", confidence);
      let confidence = (info.confidence() * 100.0).round() / 100.0; 

confidence is documented as returning a value between 0 and 1, so if you want the percentage, you want to just multiply by 100.0. You can use formatting to only print so many digits after the decimal point:

    let x = 100.0 * 0.00287;
    println!("{}", x);    // 0.287
    println!("{:.0}", x); // 0
    println!("{:.1}", x); // 0.3
    println!("{:.2}", x); // 0.29
    println!("{:.3}", x); // 0.287
    println!("{:.4}", x); // 0.2870

However, there's no format to exclude 0 before the decimal point (or to exclude the decimal point). You could use an integer instead.

    let confidence = (info.confidence() * 100.0).round() as i8; 
    println!("Confidence: {}%", confidence);

Or you could trim the output of format!.

    let confidence = format!("{:0.2}", info.confidence());
    println!("Confidence: {}", confidence.trim_start_matches('0'));

If you know a printf-style formatting that suits your needs you can also use the gpoint crate for your output.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.