Last active
June 10, 2016 22:02
-
-
Save habnabit/f5940d387142574cd3e8e1685c945092 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn float_precision(v: f64, sig_figs: u32) -> usize { | |
let v = v.abs(); | |
if v == 0f64 { | |
return 0; | |
} | |
let prec = (v.log10().floor() - (sig_figs as f64)) as isize + 1; | |
if prec >= 0 { | |
0 | |
} else { | |
-prec as usize | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::float_precision; | |
parametrize_test!{test_float_precision_formatting, [ | |
(v: f64, s: u32, r: &'static str), | |
(100f64, 2, "100"), | |
( 10f64, 2, "10"), | |
( 1f64, 2, "1.0"), | |
( 0f64, 2, "0"), | |
( 0.1f64, 2, "0.10"), | |
(123.456f64, 2, "123"), | |
( 23.456f64, 2, "23"), | |
( 3.456f64, 2, "3.5"), | |
( 0.456f64, 2, "0.46"), | |
( 0.056f64, 2, "0.056"), | |
( 0.00078f64, 2, "0.00078"), | |
(100f64, 3, "100"), | |
( 10f64, 3, "10.0"), | |
( 1f64, 3, "1.00"), | |
( 0f64, 3, "0"), | |
( 0.1f64, 3, "0.100"), | |
(123.456f64, 3, "123"), | |
( 23.456f64, 3, "23.5"), | |
( 3.456f64, 3, "3.46"), | |
( 0.456f64, 3, "0.456"), | |
( 0.056f64, 3, "0.0560"), | |
( 0.00078f64, 3, "0.000780"), | |
], { | |
assert_eq!(format!("{:.*}", float_precision(v, s), v), r); | |
}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment