Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Fix FormCalc Str() printing small negative numbers as "-0" (#4108)

NetterSilverc32c2ce09f00
diff --git a/crates/js/src/formcalc.rs b/crates/js/src/formcalc.rs
index 4ff77b74c..4b955ef9f 100644
--- a/crates/js/src/formcalc.rs
+++ b/crates/js/src/formcalc.rs
@@ -716,6 +716,8 @@ fn num_text(n: f64) -> String {
fn fixed(v: f64, decimals: usize) -> String {
let k = 10f64.powi(decimals.min(20) as i32);
let scaled = (v * k).round() / k;
+ // A small negative value rounds to -0.0, which would print as "-0".
+ let scaled = if scaled == 0.0 { 0.0 } else { scaled };
format!("{:.decimals$}", if scaled.is_finite() { scaled } else { v })
}
@@ -2627,6 +2629,14 @@ pub fn run_formcalc_within(script: &str, event: &XfaEvent, doc: &XfaDoc, root: X
mod tests {
use super::*;
+ #[test]
+ fn fixed_does_not_print_negative_zero() {
+ assert_eq!(fixed(-0.4, 0), "0");
+ assert_eq!(fixed(-0.004, 2), "0.00");
+ assert_eq!(fixed(-0.0, 0), "0");
+ assert_eq!(fixed(-1.5, 0), "-2");
+ }
+
#[test]
fn dates_round_trip_through_formcalc_day_numbers() {
assert_eq!(days_from_civil(1900, 1, 1), 1);