diff --git a/README.md b/README.md index 1c2ae2b..998a0f1 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/javascript/formatting-values-with-units-for-display.md b/javascript/formatting-values-with-units-for-display.md new file mode 100644 index 0000000..62b5d29 --- /dev/null +++ b/javascript/formatting-values-with-units-for-display.md @@ -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)