mirror of
https://github.com/storytold/cadcraft.git
synced 2026-10-19 02:09:48 -05:00
Print signed two-digit exponent for scientific units (LUNITS 1) (#1386)
Found while testing crates/engine/src/units.rs:13 Co-authored-by: Claude Haiku 5.5 <noreply@anthropic.com> Co-authored-by: Brandon Thomas <echelon@gmail.com>
This commit is contained in:
1 file changed
+27
-1
@@ -10,7 +10,7 @@ pub fn format_distance(v: f64, lunits: i64, luprec: i64) -> String {
|
||||
}
|
||||
let prec = luprec.clamp(0, 8) as usize;
|
||||
match lunits {
|
||||
1 => format!("{:.*E}", prec, v),
|
||||
1 => scientific(v, prec),
|
||||
3 => {
|
||||
let neg = v < 0.0;
|
||||
// Round at the displayed precision before splitting, so 11.999 carries to 1'-0.00".
|
||||
@@ -57,6 +57,21 @@ pub fn format_distance(v: f64, lunits: i64, luprec: i64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Scientific notation with a signed exponent of at least two digits (`1.7500E+01`, `1.00E-05`).
|
||||
fn scientific(v: f64, prec: usize) -> String {
|
||||
let s = format!("{:.*E}", prec, v);
|
||||
match s.split_once('E') {
|
||||
Some((mantissa, exp)) => {
|
||||
let (sign, digits) = match exp.strip_prefix('-') {
|
||||
Some(d) => ('-', d),
|
||||
None => ('+', exp),
|
||||
};
|
||||
format!("{mantissa}E{sign}{digits:0>2}")
|
||||
}
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
fn gcd(a: i64, b: i64) -> i64 {
|
||||
if b == 0 { a.abs().max(1) } else { gcd(b, a % b) }
|
||||
}
|
||||
@@ -348,6 +363,17 @@ mod tests {
|
||||
assert_eq!(format_distance(11.6, 3, 0), "1'-0\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scientific_exponent_is_signed_and_padded() {
|
||||
assert_eq!(format_distance(17.5, 1, 4), "1.7500E+01");
|
||||
assert_eq!(format_distance(0.00001, 1, 2), "1.00E-05");
|
||||
assert_eq!(format_distance(1234.5, 1, 3), "1.234E+03");
|
||||
assert_eq!(format_distance(12345678.0, 1, 3), "1.235E+07");
|
||||
assert_eq!(format_distance(-17.5, 1, 4), "-1.7500E+01");
|
||||
assert_eq!(format_distance(0.0, 1, 2), "0.00E+00");
|
||||
assert_eq!(format_distance(1e100, 1, 1), "1.0E+100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dms_display_precision() {
|
||||
let angle = (12.0 + 34.0 / 60.0 + 56.78912 / 3600.0_f64).to_radians();
|
||||
|
||||
Reference in new issue
Block a user