Convert integer to two decimal point String

I have a u64 representing a two-decimal point number (eg 1.23 * 100).

What is the best way to convert it to a String whilst including the decimal point?

For example:

fn dp_string(amount: u64) -> String {
    let mut s = amount.to_string();
    match s.len() {
        1 => format!("0.0{}", s),
        2 => format!("0.{}", s),
        _ => {
            s.insert(s.len() - 2, '.');
            s
        }
    }
}

This can be done by converting it to a floating-point number:

fn dp_string(amount: u64) -> String {
    format!("{:.2}", amount as f64 / 100.0)
}

However, this may give incorrect results on larger numbers. So we can alternatively do some modular arithmetic to separate the integer part from the fractional part:

fn dp_string(amount: u64) -> String {
    format!("{}.{:02}", amount / 100, amount % 100)
}
5 Likes

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.