So although we used prefix and suffix to add some formatting before and after the values, we can also use the formatter function to format the values in any way we like.
The formatter function is passed the value, index and percent of the pip/handle to allow us to modify the display.
<RangeSliderformatter={(value, index, percent) => { return value }} />
Pips and Floats
There are two properties that deal with formatting; formatter and handleFormatter. These are for the pips and handles respectively. If the handleFormatter is not set, then the formatter will be used for both.
Single Formatter
Like in the prefix example, where we added a simple € prefix. This time we will also style as a currency, but we will format the whole number into a currency string using the Intl.NumberFormat API.
Here we will use the same formatter example as above for displaying the handleFormatter, but we will use a different formatter for the pip labels to demonstrate how you can use different formatters for each.
Here’s a pretty intense example, where we use the formatter to convert the values into Gigabytes, Terabytes, Petabytes, etc. There’s a pretty hefty algorithm to scale the values logarithmically, and then a special function for styling the numbers as Giga, Tera, Peta, etc.
<script>let values = [1];// format the value to a human readable stringconstformatter= (value) => {constgigabyte=1000000000;returnprettyBytes( toGigabytes(value) * gigabyte );// https://github.com/sindresorhus/pretty-bytes }// take the input value from the range, and then// power it so it outputs in a logarithmic scaleconsttoGigabytes= (value) => {if (value <=10) return value;constMOD= (val, div) => val % div;constPOW= (base, exp) => Math.pow(base, exp);constCEIL= (val) => Math.ceil(val);constMAX= (val, val2) => Math.max(val, val2);constMODULO=MAX( 1, value -1-MOD(value -11, 9 ));constPOWER=POW( 10, CEIL( MODULO/10 ));return ( value -MODULO ) *POWER+POWER; }</script><RangeSlider{formatter}floatpipsall="label"min={1} max={55} pipstep={9} range="min"bind:values />
Squares
One last example of handle and pip formatters working to compliment each other. This time we will use the handleFormatter to show the real value, and the formatter to show the square of the value.
<script>let values = [7];</script><RangeSliderformatter={v=> v +"²"} handleFormatter={v=> v * v} floatpipsall="label"max={15} bind:values />