Skip to content

Commit b2a5a6c

Browse files
committed
fix: Apply minFractionDigits only to decimal strings (#676)
1 parent 93c951b commit b2a5a6c

3 files changed

Lines changed: 31 additions & 12 deletions

File tree

src/nodes/Scalar.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,11 @@ export class Scalar<T = unknown> extends NodeBase {
4343
*/
4444
declare format?: string
4545

46-
/** If `value` is a number, use this value when stringifying this node. */
46+
/**
47+
* If `value` is a number that is serialized as a decimal string
48+
* (i.e. not using exponential notation),
49+
* use this value when stringifying this node.
50+
*/
4751
declare minFractionDigits?: number
4852

4953
/** Set during parsing to the source string value */

src/stringify/stringifyNumber.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ export function stringifyNumber({
1414
!format &&
1515
minFractionDigits &&
1616
(!tag || tag === 'tag:yaml.org,2002:float') &&
17-
/^\d/.test(n)
17+
/^-?\d/.test(n) &&
18+
!n.includes('e')
1819
) {
1920
let i = n.indexOf('.')
2021
if (i < 0) {

tests/doc/stringify.ts

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,30 @@ for (const [name, version] of [
4747
expect(YAML.stringify(-0, { version })).toBe('-0\n')
4848
})
4949

50-
test('float with trailing zeros', () => {
51-
const doc = new YAML.Document<YAML.Scalar, false>(3, { version })
52-
doc.contents.minFractionDigits = 2
53-
expect(String(doc)).toBe('3.00\n')
54-
})
55-
test('scientific float ignores minFractionDigits', () => {
56-
const doc = new YAML.Document<YAML.Scalar, false>(3, { version })
57-
doc.contents.format = 'EXP'
58-
doc.contents.minFractionDigits = 2
59-
expect(String(doc)).toBe('3e+0\n')
50+
describe('minFractionDigits', () => {
51+
for (const [n, exp] of [
52+
[3, '3.00\n'],
53+
[-3, '-3.00\n'],
54+
[4.2, '4.20\n'],
55+
[4.21, '4.21\n'],
56+
[4.215, '4.215\n'],
57+
[0, '0.00\n'],
58+
[-0, '-0.00\n'],
59+
[1e32, '1e+32\n'],
60+
]) {
61+
test(`number (${n}) with trailing zeros`, () => {
62+
const doc = new YAML.Document<YAML.Scalar, false>(n, { version })
63+
doc.contents.minFractionDigits = 2
64+
expect(doc.toString()).toBe(exp)
65+
})
66+
}
67+
68+
test('scientific float ignores minFractionDigits', () => {
69+
const doc = new YAML.Document<YAML.Scalar, false>(3, { version })
70+
doc.contents.format = 'EXP'
71+
doc.contents.minFractionDigits = 2
72+
expect(String(doc)).toBe('3e+0\n')
73+
})
6074
})
6175

6276
test('integer with HEX format', () => {

0 commit comments

Comments
 (0)