Skip to content

Commit

Permalink
format floats in dosage strings
Browse files Browse the repository at this point in the history
Use correct approach into formatting float values during converting them to strings with up-scaling to complete values.
  • Loading branch information
keinsell committed Jan 3, 2025
1 parent fdd709d commit 544bd2e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ chrono-english = "0.1.7"
clap-verbosity-flag = "3.0.1"
clap_complete = "4.5.40"
atty = "0.2.14"
ryu = "1.0.18"
float-pretty-print = "0.1.1"
[dependencies.sea-orm-migration]
version = "1.1.0"
features = [
Expand Down
20 changes: 17 additions & 3 deletions src/lib/dosage.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
use measurements::Mass;
use clap::builder::TypedValueParser;
use float_pretty_print::PrettyPrintFloat;
use measurements::{Mass, Measurement};
use miette::IntoDiagnostic;
use std::str::FromStr;

pub type Dosage = Mass;

// TODO: This is not what it's meant to be, there is a still work needed on sane
// approach to automatic scaling of units.
/// Function will take human-readable input as representation of mass of
/// substance that was ingested (also referred as Dosage)
pub fn parse_dosage(input: &str) -> miette::Result<Dosage>
{
Mass::from_str(input).into_diagnostic()
}

pub fn format_dosage(input: &Dosage) -> miette::Result<String> {
let suggested_unit = input.get_appropriate_units();
let float = format!("{:4.4}", PrettyPrintFloat(suggested_unit.1));
let unit = suggested_unit.0;
Ok(format!("{} {}", float.trim_start(), unit))
}


#[cfg(test)]
mod tests
{
Expand All @@ -28,4 +36,10 @@ mod tests
Mass::from_micrograms(100f64)
)
}

#[test]
fn test_print_dosage() {
let dosage = Mass::from_grams(0.1);
assert_eq!(format_dosage(&dosage).unwrap(), "100 mg");
}
}
6 changes: 5 additions & 1 deletion src/view_model/ingestion.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::lib::dosage::format_dosage;
use crate::lib::dosage::Dosage;
use crate::lib::orm::ingestion;
use crate::lib::output::Formatter;
use core::convert::From;
use measurements::Measurement;
use serde::Deserialize;
use serde::Serialize;
Expand All @@ -26,11 +28,13 @@ impl From<ingestion::Model> for ViewModel
{
fn from(model: ingestion::Model) -> Self
{
let dosage = Dosage::from_base_units(model.dosage.into());

Self::builder()
.id(model.id)
.substance_name(model.substance_name)
.route(model.route_of_administration)
.dosage(Dosage::from_base_units(model.dosage as f64).to_string())
.dosage(format_dosage(&dosage).unwrap())
.ingested_at(model.ingested_at.to_string())
.build()
}
Expand Down

0 comments on commit 544bd2e

Please sign in to comment.