From 69b70174c03a32ff9fc80a22c4b22557c1fc6b14 Mon Sep 17 00:00:00 2001 From: PgBiel <9021226+PgBiel@users.noreply.github.com> Date: Wed, 2 Aug 2023 01:19:18 -0300 Subject: [PATCH] fix precision on floats which are exact integers --- tests/strfmt-tests.typ | 3 +++ typst-strfmt.typ | 17 +++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/strfmt-tests.typ b/tests/strfmt-tests.typ index dcf6d9d..9811a43 100644 --- a/tests/strfmt-tests.typ +++ b/tests/strfmt-tests.typ @@ -34,6 +34,9 @@ // test taking width and precision from pos args / named args (.x$ / y$ notation) assert.eq(strfmt("{:.1$}; {woah:0france$.moment$}; {}; {2:a>1$}", 5.5399234, 9, "stringy", woah: 3.9, france: 7, moment: 2), "5.539923400; 0003.90; 9; aastringy") + // test weird precision cases + assert.eq(strfmt("{0:e} {0:+.9E} | {1:.3e} {1:.3} {2:.3} | {3:.4} {3:.4E} | {4:.2} {4:.3} {4:.5}", 124.2312, 50, 50.0, -0.02, 2.44454), "1.242312e2 +1.242312000E2 | 5.000e1 50 50.000 | -0.0200 -2.0000E-2 | 2.44 2.445 2.44454") + // test custom decimal separators (I) assert.eq(strfmt("{}; {:07e}; {}; {}; {:?}", 1.532, 45000, -5.6, "a.b", "c.d", fmt-decimal-separator: ","), "1,532; 004,5e4; -5,6; a.b; \"c.d\"") diff --git a/typst-strfmt.typ b/typst-strfmt.typ index ffb5123..94737f8 100644 --- a/typst-strfmt.typ +++ b/typst-strfmt.typ @@ -180,13 +180,22 @@ } let result = _strfmt_stringify(calc.round(float(num), digits: calc.min(50, precision))) let digits-match = result.match(regex("^\\d+\\.(\\d+)$")) + let digits-len-diff = 0 if digits-match != none and digits-match.captures.len() > 0 { + // get the digits capture group; its length will be digit amount let digits = digits-match.captures.first() - let digits-len-diff = precision - digits.len() - // add missing zeroes for precision - if digits-len-diff > 0 { - result += "0" * digits-len-diff + digits-len-diff = precision - digits.len() + } else if "." not in result { // 5.0 or something + // 0 digits! Difference will be exactly 'precision' + digits-len-diff = precision + } + + // add missing zeroes for precision + if digits-len-diff > 0 { + if "." not in result { + result += "." // decimal separator missing } + result += "0" * digits-len-diff } result