mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Formatting Values With Units For Display as a javascript til
This commit is contained in:
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_878 TILs and counting..._
|
||||
_879 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -297,6 +297,7 @@ _878 TILs and counting..._
|
||||
- [Fill An Input With A Ton Of Text](javascript/fill-an-input-with-a-ton-of-text.md)
|
||||
- [Find Where Yarn Is Installing Binaries](javascript/find-where-yarn-is-installing-binaries.md)
|
||||
- [for...in Iterates Over Object Properties](javascript/for-in-iterates-over-object-properties.md)
|
||||
- [Formatting Values With Units For Display](javascript/formatting-values-with-units-for-display.md)
|
||||
- [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md)
|
||||
- [Generate Random Integers](javascript/generate-random-integers.md)
|
||||
- [Get The Location And Size Of An Element](javascript/get-the-location-and-size-of-an-element.md)
|
||||
|
||||
34
javascript/formatting-values-with-units-for-display.md
Normal file
34
javascript/formatting-values-with-units-for-display.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Formatting Values With Units For Display
|
||||
|
||||
There are all kinds of values and units your app may need to display. The
|
||||
[`Intl.NumberFormat`
|
||||
API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat)
|
||||
that is available in modern browsers can help with standardizing that display.
|
||||
|
||||
How about formatting distances for display?
|
||||
|
||||
Here is a compact formatting of miles:
|
||||
|
||||
```javascript
|
||||
> const milesFormat =
|
||||
Intl.NumberFormat("en-US", { style: "unit", unit: "mile" });
|
||||
> milesFormat.format(1500)
|
||||
"1,500 mi"
|
||||
```
|
||||
|
||||
Here is two different formats for kilometers:
|
||||
|
||||
```javascript
|
||||
> const kmFormat =
|
||||
Intl.NumberFormat("en-US", { style: "unit", unit: "kilometer" });
|
||||
> kmFormat.format(1500)
|
||||
"1,500 km"
|
||||
> const kilometerFormat =
|
||||
Intl.NumberFormat("en-US", { style: "unit", unit: "kilometer", unitDisplay: "long" })
|
||||
> kilometerFormat.format(1500)
|
||||
"1,500 kilometers"
|
||||
```
|
||||
|
||||
Give it a try with something else like `miles-per-hour`, `liter`, or `gallon`.
|
||||
|
||||
[source](https://twitter.com/jamesreggio/status/1196574375916400640?s=21)
|
||||
Reference in New Issue
Block a user