snippetjavascriptTip
Formatting numeric values in JavaScript
Viewed 0 times
formattingjavascriptnumericvalues
Problem
Number formatting is one of the most common presentational tasks you'll encounter coding for the web. While there are some built-in methods, it's often necessary to roll up your own solution for a specific use case. Let's explore a few common scenarios and how to handle them.
> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
In fixed-point notation, a number is represented with a fixed number of digits after the decimal point. However, we often want to remove trailing zeros from the result.
> [!NOTE]
>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
In fixed-point notation, a number is represented with a fixed number of digits after the decimal point. However, we often want to remove trailing zeros from the result.
Solution
const toOptionalFixed = (num, digits) =>
`${Number.parseFloat(num.toFixed(digits))}`;
toOptionalFixed(1, 2); // '1'
toOptionalFixed(1.001, 2); // '1'
toOptionalFixed(1.500, 2); // '1.5'>
> You may not be familiar with JavaScript's numeric separators, which are used in the examples below. They're syntactic sugar that make large numeric values more readable.
In fixed-point notation, a number is represented with a fixed number of digits after the decimal point. However, we often want to remove trailing zeros from the result.
In order to do so, we can use
Number.prototype.toFixed() to convert the number to a fixed-point notation string. Then, using Number.parseFloat(), we can convert the fixed-point notation string to a number, removing trailing zeros. Finally, we can use a template literal to convert the number to a string.Rounding a number to a specific number of decimal places is pretty common. We can use
Math.round() and template literals to round the number to the specified number of digits. Omitting the second argument, decimals, will round to an integer.> [!NOTE]
Code Snippets
const toOptionalFixed = (num, digits) =>
`${Number.parseFloat(num.toFixed(digits))}`;
toOptionalFixed(1, 2); // '1'
toOptionalFixed(1.001, 2); // '1'
toOptionalFixed(1.500, 2); // '1.5'const round = (n, decimals = 0) =>
Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
day: Math.floor(ms / 86_400_000),
hour: Math.floor(ms / 3_600_000) % 24,
minute: Math.floor(ms / 60_000) % 60,
second: Math.floor(ms / 1_000) % 60,
millisecond: Math.floor(ms) % 1_000
};
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ');
};
formatDuration(1_001);
// '1 second, 1 millisecond'
formatDuration(34_325_055_574);
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'Context
From 30-seconds-of-code: number-formatting
Revisions (0)
No revisions yet.