Skip to content

Commit

Permalink
fix precision on floats which are exact integers
Browse files Browse the repository at this point in the history
  • Loading branch information
PgBiel committed Aug 2, 2023
1 parent 68888bf commit 69b7017
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
3 changes: 3 additions & 0 deletions tests/strfmt-tests.typ
Original file line number Diff line number Diff line change
Expand Up @@ -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\"")

Expand Down
17 changes: 13 additions & 4 deletions typst-strfmt.typ
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 69b7017

Please sign in to comment.