SergioB-dev / rust-regex-pro

CLI Regex Trainer - A collaborative rust project for regex enthusiasts
0 stars 2 forks source link

On User's struct pct function, multiply by 100 #11

Open gabucito opened 2 years ago

gabucito commented 2 years ago

The current pct function shows %: 1 when it should probably be %: 100.

I would suggest multiplying it to 10,000, round it and then divide it by 100.0 in order to get a percentage up to 2 decimals.

let total = (self.correct + self.wrong) as f32;
if total == 0.0 {
    // If total is 0, compiler will see it as NaN
    0.0
} else {
    (self.correct as f32 / total * 10000.0).round() / 100.0
}

Another way would be to just multiply by 100 and let the print formatted take care of the decimals

let total = (self.correct + self.wrong) as f32;
if total == 0.0 {
    // If total is 0, compiler will see it as NaN
    0.0
} else {
    self.correct as f32 / total * 100.0
}

Use {:.2} so that the print formatted prints up to 2 decimals only

println!(
    "\t%: {:.2} \tScore: {} \tRank: {}",
    user_win_pct, user_score, user_ranking
);
PavlosMac commented 2 years ago

This will be fixed in #2 once merged.

From issue 2 solution:

pub fn pct(&self) -> f32 {
        let total = (self.correct + self.wrong) as f32;
        if total == 0.0 {
            // If total is 0, compiler will see it as NaN
            0.0
        } else {
            (self.correct as f32 / total) * 100.00
        }
    }