| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Round a value to `k` digits after the decimal point (`toFixed` semantics), |
| 34 | * returning the fixed-point string (used by the number-display |
| 35 | * `{ fractional: k }` control). May include trailing zeros (e.g. `2` → `2.00`). |
| 36 | */ |
| 37 | export function roundToDecimalPlace( |
| 38 | value: number | BigDecimal, |
| 39 | k: number |
| 40 | ): string { |
| 41 | // `toFixed` accepts at most 100 digits. For a machine number with a smaller |
| 42 | // magnitude than that allows (a value next to 1e-300 with an error 1e-9 |
| 43 | // times smaller), write the number in exponential notation with the same |
| 44 | // last decimal place instead of throwing a `RangeError` (CE-185.8). |
| 45 | if (typeof value === 'number' && k > 100 && Number.isFinite(value)) { |
| 46 | if (value === 0) return '0'; |
| 47 | const exponent = parseInt(value.toExponential().split('e')[1], 10); |
| 48 | // The first digit is at the place `10^exponent`. When it is past the |
| 49 | // requested place `10^-k`, the value rounds to `0`, or to one unit of |
| 50 | // that place when it is at least half of it. |
| 51 | if (exponent + k < 0) { |
| 52 | if (exponent + k === -1 && Math.abs(value) >= 0.5 * 10 ** -k) |
| 53 | return `${value < 0 ? '-' : ''}1e-${k}`; |
| 54 | return '0'; |
| 55 | } |
| 56 | return value.toExponential(Math.min(100, exponent + k)); |
| 57 | } |
| 58 | return value.toFixed(k); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Validate a `digits` serialization option ({@link DisplayDigits}) and return |
| 63 | * it with `n` rounded to an integer, or `undefined` when no option is given. |
| 64 | * |
| 65 | * The accepted values are `'auto'`, `'max'`, `{ significant: n }` with |
| 66 | * `n ≥ 1` and `{ fractional: n }` with `n ≥ 0`. Any other value, a bare |
| 67 | * number included, throws an `Error` that names the accepted values: a |
| 68 | * misspelled option fails at once instead of being ignored. (A bare number |
| 69 | * was accepted until the `fractionalDigits` option was removed, with that |
| 70 | * option's convention; it is no longer.) |
| 71 | * |
| 72 | * The MathJSON, LaTeX and AsciiMath serializers all call this function, so |
| 73 | * they accept and reject the same values. |
| 74 | */ |
| 75 | export function validateDisplayDigits(d: unknown): DisplayDigits | undefined { |
| 76 | if (d === undefined || d === 'auto' || d === 'max') return d; |
| 77 | if (typeof d === 'object' && d !== null) { |
| 78 | const v = d as { significant?: unknown; fractional?: unknown }; |
| 79 | if ( |
| 80 | typeof v.significant === 'number' && |
| 81 | Number.isFinite(v.significant) && |
| 82 | v.significant >= 1 |
| 83 | ) |
| 84 | return { significant: Math.round(v.significant) }; |
| 85 | if ( |
| 86 | typeof v.fractional === 'number' && |
| 87 | Number.isFinite(v.fractional) && |
| 88 | v.fractional >= 0 |
| 89 | ) |