Skip to content

Float rounding with specified digits #3608

@amab8901

Description

@amab8901

Introduce method round_to_digits(T: u32) for f64 (and f32). Same as f64::round() except that you can specify how many digits you want to round to.

Example use case:

I have the number 12.34567 and I want to round it to 12.35. Current f64::round() requires a verbose/less-readable/bug-prone workaround:

let full_float = 12.34567;
let rounded_float = (full_float * 100.0).round() / 100.0;
assert_eq!(rounded_float, 12.35);

The proposed method round_to() would simplify the above to:

let rounded_float = 12.34567.round_to_digits(2);
assert_eq!(rounded_float, 12.35);

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions