Skip to content

Instantly share code, notes, and snippets.

@voscausa
Last active August 8, 2020 20:33
Show Gist options
  • Save voscausa/38fff5dfa5bc3c238155a9762b16d3c7 to your computer and use it in GitHub Desktop.
Save voscausa/38fff5dfa5bc3c238155a9762b16d3c7 to your computer and use it in GitHub Desktop.
Euro currency formatting in Svelte 3 using various options
<script>
import { toEur, setFormat } from './use_format.js';
let num = -5;
setFormat('currency', {style: 'currency', zero:false});
function handleClick() {
num <= 0 ? num +=1 : num-=4;
}
</script>
<style>
p {
font-style: italic;
font-family: 'Courier New', Courier, monospace
}
span {
font-weight: bold;
font-style: initial;
}
</style>
<h3>Reactive euro formatting</h3>
<p>decimal_0: <span use:toEur={num}></span> setFormat default options(style: 'decimal', zero:true)</p>
<p>currency: <span use:toEur={num, 'currency'}></span> setFormat options(style: 'currency', zero:false)</p>
<button on:click={handleClick}>
Click {num}
</button>
const formats = {}; // temp formasts store
const default_options = {
style: "decimal", // "currency" || "decimal",
currency: "EUR",
useGrouping: true,
minimumFractionDigits: 2,
zero: true // show 0 || ''; Not a NumberFormat option!
};
export function setFormat(fId, options) {
// merge options and init formatter
const format_options = { ...default_options, ...options };
formats[fId] = {
options: format_options,
formatter: new Intl.NumberFormat("nl-NL", format_options),
};
console.log('setFormat', fId, format_options)
};
setFormat('decimal_0', {});
// Example: setFormat('currency', {style: 'currency', zero:false});
function formatNode(node, num, formatObj) {
// format Node (num) using the formatObj initialized formatter (options)
let number = ('' + num).trim();
// handle the zero option
if (formatObj.options.zero === false && (number === '0' || number === '')) node.innerText = '';
else {
node.textContent = formatObj.formatter.format(((number || 0) / 100).toFixed(2));
Object.assign(node.style, {
color: number.startsWith('-') ? 'red' : 'inherit'
});
}
}
// <p>default: <span use:toEur={num}></span></p>
// <p>currency: <span use:toEur={num, 'currency'}></span></p>
export function toEur(node, num, fId = 'decimal_0') {
// the node has been mounted in the DOM
formatNode(node, num, formats[fId])
return {
update(num) { // make it reactive
// console.log('use_format updated', num, fId);
formatNode(node, num, formats[fId]);
// the value of `bar` has changed
},
destroy() {
// the node has been removed from the DOM
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment