feat(shopping): formatQuantity-Utility
Some checks failed
Build & Publish Docker Image / build-and-push (push) Has been cancelled
Some checks failed
Build & Publish Docker Image / build-and-push (push) Has been cancelled
This commit is contained in:
7
src/lib/quantity-format.ts
Normal file
7
src/lib/quantity-format.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
export function formatQuantity(q: number | null): string {
|
||||||
|
if (q === null || q === undefined) return '';
|
||||||
|
const rounded = Math.round(q);
|
||||||
|
if (Math.abs(q - rounded) < 0.01) return String(rounded);
|
||||||
|
// auf max. 2 Nachkommastellen, trailing Nullen raus
|
||||||
|
return q.toFixed(2).replace(/\.?0+$/, '');
|
||||||
|
}
|
||||||
28
tests/unit/quantity-format.test.ts
Normal file
28
tests/unit/quantity-format.test.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { formatQuantity } from '../../src/lib/quantity-format';
|
||||||
|
|
||||||
|
describe('formatQuantity', () => {
|
||||||
|
it('renders null as empty string', () => {
|
||||||
|
expect(formatQuantity(null)).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders whole numbers as integer', () => {
|
||||||
|
expect(formatQuantity(400)).toBe('400');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders near-integer as integer (epsilon 0.01)', () => {
|
||||||
|
expect(formatQuantity(400.001)).toBe('400');
|
||||||
|
expect(formatQuantity(399.999)).toBe('400');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders fractional with up to 2 decimals, trailing zeros trimmed', () => {
|
||||||
|
expect(formatQuantity(0.5)).toBe('0.5');
|
||||||
|
expect(formatQuantity(0.333333)).toBe('0.33');
|
||||||
|
expect(formatQuantity(1.1)).toBe('1.1');
|
||||||
|
expect(formatQuantity(1.1)).toBe('1.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles zero', () => {
|
||||||
|
expect(formatQuantity(0)).toBe('0');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user