rust-embedded-community / rust-measurements

Metric, Imperial, and other measurement handling for Rust. Length, Temperature, Weight, and Volume
https://crates.io/crates/measurements
27 stars 10 forks source link

'pick_appropriate_units()': precision versus prettiness #24

Closed alberdingk-thijm closed 3 years ago

alberdingk-thijm commented 5 years ago

I noticed recently that, due to the strict bounds checking in pick_appropriate_units() in src/measurement.rs, that the following code was not producing the output I was expecting:

extern crate measurements;
use measurements::*;

fn main() {
    let val : f64 = 1.0;
    println!("Mass of {0:.3}", Mass::from_kilograms(val));
    println!("Length of {0:.3}", Length::from_meters(val));
    println!("Volume of {0:.3}", Volume::from_litres(val));
}

prints the following:

Mass of 1000.000 g
Length of 100.000 cm
Volume of 1000.000 ml

whereas I had expected it to print:

Mass of 1.000 kg
Length of 1.000 m
Volume of 1.000 l

I figure the former is perhaps more precise, but seemed a bit ugly for display when dealing with units which didn't need that precision, particularly given that if I change val to be 1.00000000001, I get the output I was expecting (due to precision formatting).

I've gone and updated my branch to use the latter by changing value > 1.0 || value < -1.0 to value >= 1.0 || value <= -1.0 in pick_appropriate_units(). If this is something that is generally more useful, or something to offer as an opt-in, I'd be happy to submit a PR.

thejpster commented 5 years ago

I agree. Please do send a PR.

alberdingk-thijm commented 5 years ago

Sorry for the radio silence. I had noticed some values still printed strangely, but was distracted by other work. I'll take some time to look into it later this week and make a PR.

Absolucy commented 3 years ago

Was this ever fixed?

alberdingk-thijm commented 3 years ago

I never followed up on my "threat", unfortunately! Anyone else is welcome to beat me to making the PR; I think my branch has a working solution, so I can submit a PR later today too.

alberdingk-thijm commented 3 years ago

PR has been submitted!