Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/core/xlsx/numfmt.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Excel number-format subset: General, fixed/grouped/percent/scientific/fraction, dates & times, sections & colors. */
import { dict } from '../dict'
import { pickSection, roundHalf } from './formula/format'
import { pickSection } from './formula/format'

export const BUILTIN_FORMATS: Record<number, string> = {
0: 'General', 1: '0', 2: '0.00', 3: '#,##0', 4: '#,##0.00', 9: '0%', 10: '0.00%', 11: '0.00E+00',
Expand Down Expand Up @@ -199,6 +199,23 @@ function group(intStr: string): string {
return intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

/** Round a nonnegative value's 15 significant decimal digits without returning to binary. */
function fixedDecimal(v: number, decimals: number): string {
if (!Number.isFinite(v)) return String(v)
const [mantissa, exponent] = v.toExponential(14).split('e')
let coefficient = BigInt(mantissa.replace('.', ''))
const shift = Number(exponent) - 14 + decimals
let digits: string
if (shift >= 0) digits = coefficient.toString() + '0'.repeat(shift)
else {
const divisor = 10n ** BigInt(-shift)
coefficient = (coefficient + divisor / 2n) / divisor
digits = coefficient.toString()
}
digits = digits.padStart(decimals + 1, '0')
return decimals ? digits.slice(0, -decimals) + '.' + digits.slice(-decimals) : digits
}

function formatNumber(v: number, sec: Section): string {
const toks = sec.toks
let val = Math.abs(v)
Expand Down Expand Up @@ -234,11 +251,12 @@ function formatNumber(v: number, sec: Section): string {
mant = mant / Math.pow(10, exp)
}
}
// toFixed on the raw double rounds 2.675 down; Excel rounds the 15-digit decimal value
let fixed = roundHalf(mant, decCount).toFixed(decCount)
// Keep the rounded decimal digits: converting back to a double can add spurious digits
// at large magnitudes, and toFixed switches to exponential notation at 1e21.
let fixed = fixedDecimal(mant, decCount)
if (expIdx >= 0 && Number(fixed) >= 10 && toks.slice(0, intEnd).filter((t) => t.k === 'digit').length <= 1) {
exp += 1
fixed = roundHalf(mant / 10, decCount).toFixed(decCount)
fixed = fixedDecimal(mant / 10, decCount)
}
let [intPart, decPart = ''] = fixed.split('.')
// decimals: # trims trailing zeros, ? pads with spaces
Expand Down Expand Up @@ -362,8 +380,8 @@ export function serialToDate(serial: number, date1904 = false): Date {
function formatDate(v: number, sec: Section, date1904: boolean): string {
const toks = sec.toks
const hasAmPm = toks.some((t) => t.k === 'date' && /^(am\/pm|a\/p)$/i.test(t.v ?? ''))
// Excel rounds the time to the smallest unit shown (seconds, or the digits of ".0") and only
// then splits it into fields, so 23:59:59.6 shown as h:mm:ss carries into the next day.
// Excel rounds to seconds (also for date-only formats), or the digits of ".0", before
// splitting into fields, so 23:59:59.6 carries into the next day even with m/d/yyyy.
const fracDigits = Math.min(3, Math.max(0, ...toks.map((t) => (t.k === 'date' && t.v[0] === '.' ? t.v.length - 1 : 0))))
const unit = Math.pow(10, fracDigits)
let day = Math.floor(v)
Expand Down
49 changes: 49 additions & 0 deletions test/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,61 @@ describe('numfmt', () => {
expect(f(1.5, '# ?/?')).toBe('1 1/2')
expect(f(-3, '0')).toBe('-3')
})
test('large fixed decimals retain decimal precision rather than binary digits', () => {
// Excel 16.115 also displays the adjacent doubles as 1e21 at 15 significant digits.
for (const v of [1e21 - 131072, 1e21, 1e21 + 131072]) {
expect(f(v, '0.00')).toBe('1000000000000000000000.00')
expect(f(-v, '0.00')).toBe('-1000000000000000000000.00')
}
expect(f(1e21 - 1e7, '0.00')).toBe('999999999999990000000.00')
expect(f(1e21 + 1e7, '0.00')).toBe('1000000000000010000000.00')
expect(f(1.23456789012345e21, '0.00')).toBe('1234567890123450000000.00')
expect(f(1e20, '0.00')).toBe('100000000000000000000.00')
expect(f(1e100, '0.00')).toBe('1' + '0'.repeat(100) + '.00')
expect(f(-1e308, '0.00')).toBe('-1' + '0'.repeat(308) + '.00')
expect(f(Number.MAX_VALUE, '0.00')).toBe('179769313486232' + '0'.repeat(294) + '.00')
})
test('decimal rendering preserves format sections, scaling and other number formats', () => {
expect(formatValue(-1e21, '#,##0.00;[Red](#,##0.00)')).toEqual({
text: '(1,000,000,000,000,000,000,000.00)', color: '#ff0000',
})
expect(f(1e21, '[>=100]0.00;"small"')).toBe('1000000000000000000000.00')
expect(f(1e21, '0.00,,')).toBe('1000000000000000.00')
expect(f(1e21, '0.00%')).toBe('100000000000000000000000.00%')
expect(f(1e21, '0.##')).toBe('1000000000000000000000.')
expect(f(1e21, '0.??')).toBe('1000000000000000000000. ')
expect(f(1.234567890123456, '0.00000000000000000000')).toBe('1.23456789012346000000')
expect(f(9.999, '0.00E+00')).toBe('1.00E+01')
expect(f(1e100, '0.00E+00')).toBe('1.00E+100')
expect(f(1e-100, '0.00E+00')).toBe('1.00E-100')
expect(f(12345, '##0.0E+0')).toBe('12.3E+3')
expect(f(0.125, '# ?/?')).toBe('1/8')
})
test('dates', () => {
expect(f(45291.75, 'yyyy-mm-dd hh:mm')).toBe('2023-12-31 18:00')
expect(f(45291.75, 'dddd, mmmm d, yyyy h:mm AM/PM')).toBe('Sunday, December 31, 2023 6:00 PM')
expect(f(45291, 'm/d/yyyy')).toBe('12/31/2023')
expect(f(1.5, '[h]:mm:ss')).toBe('36:00:00')
})
test('date-only midnight carry matches Excel in both date systems', () => {
// Verified with Excel 16.115: date-only formats also round to seconds.
expect(f(0.99999999, 'm/d/yyyy')).toBe('1/1/1900')
expect(f(45291.99999999, 'm/d/yyyy')).toBe('1/1/2024')
expect(f(45291 + (86400 - 0.6) / 86400, 'm/d/yyyy')).toBe('12/31/2023')
expect(f(45291 + (86400 - 0.4) / 86400, 'm/d/yyyy')).toBe('1/1/2024')
expect(formatValue(0.5, 'm/d/yyyy', true).text).toBe('1/1/1904')
expect(formatValue(0.99999999, 'm/d/yyyy', true).text).toBe('1/2/1904')
expect(formatValue((86400 - 0.6) / 86400, 'm/d/yyyy', true).text).toBe('1/1/1904')
})
test('time carry preserves wrapped, elapsed and fractional seconds', () => {
const nearMidnight = (86400 - 0.4) / 86400
expect(f(nearMidnight, 'h:mm:ss')).toBe('0:00:00')
expect(f(1 + nearMidnight, 'h:mm:ss')).toBe('0:00:00')
expect(f(1 + nearMidnight, '[h]:mm:ss')).toBe('48:00:00')
expect(f((86400 - 0.04) / 86400, 'h:mm:ss.0')).toBe('0:00:00.0')
expect(f((86400 - 0.06) / 86400, 'h:mm:ss.0')).toBe('23:59:59.9')
expect(f(-0.00001, 'h:mm:ss')).toBe('########')
})
// https://github.com/p10node/office-engine/issues/3
test('matches Excel on the issue #3 repros', () => {
expect(f(-1.5, '# ?/?')).toBe('-1 1/2')
Expand Down
Loading