|
1
|
import { isEmpty } from "./is-empty" |
|
2
|
|
|
3
|
/** |
|
4
|
* Inventory quantities can be fractional when stock is held in a unit of |
|
5
|
* measure that is sold in fractions of itself, e.g. a pound sold as quarter |
|
6
|
* pounds. Rounding at four decimals keeps quarters, eighths and sixteenths |
|
7
|
* intact while hiding float artifacts from subtractions such as |
|
8
|
* `stocked_quantity - reserved_quantity`. |
|
9
|
*/ |
|
10
|
const MAX_FRACTION_DIGITS = 4 |
|
11
|
|
|
12
|
const quantityFormatter = new Intl.NumberFormat(undefined, { |
|
13
|
maximumFractionDigits: MAX_FRACTION_DIGITS, |
|
14
|
}) |
|
15
|
|
|
16
|
/** |
|
17
|
* Formats an inventory quantity for display, appending the inventory item's |
|
18
|
* unit of measure when one is set. For example, a shared pound pool reads as |
|
19
|
* "98.25 lb" rather than just "98.25" when the unit of measure is "lb". |
|
20
|
*/ |
|
21
|
export const formatQuantity = ( |
|
22
|
rawQuantity?: unknown, |
|
23
|
unitOfMeasure?: string | null |
|
24
|
) => { |
|
25
|
if (isEmpty(rawQuantity)) { |
|
26
|
return "-" |
|
27
|
} |
|
28
|
|
|
29
|
if (typeof rawQuantity !== "number" && typeof rawQuantity !== "string") { |
|
30
|
return "-" |
|
31
|
} |
|
32
|
|
|
33
|
const quantity = ( |
|
34
|
typeof rawQuantity === "string" ? parseFloat(rawQuantity) : rawQuantity |
|
35
|
)! |
|
36
|
|
|
37
|
if (isNaN(quantity)) { |
|
38
|
return "-" |
|
39
|
} |
|
40
|
|
|
41
|
const formatted = quantityFormatter.format(quantity!) |
|
42
|
|
|
43
|
return unitOfMeasure ? `${formatted} ${unitOfMeasure}` : formatted |
|
44
|
} |