Formatting numbers the Right Way

Node.JS and modern browsers all support the INTL library natively. That library has lots of features for formatting things to a locale specific format including dates and numbers.

So here is a cheeky little JavaScript function that you should be able to use either in a Node-RED function node or in custom browser code:

function dp(inp, dp, int) {
    if (!int) int = 'en-GB'
    if (!dp) dp = 1
    return inp.toLocaleString(int, { 'minimumFractionDigits': dp, 'maximumFractionDigits': dp })

Called like: msg.payload = dp(msg.payload) It would convert an input number like 12345678.12345 to an output string like "12,345,678.1". If you were to use a European format, the comma and dot would be reversed.

Of course, as shown, it only specifies the locale to use and the number of decimal places to show (it rounds by default but that can also be changed). You can do lots of tweaks to this and there are some pre-defined number formats such as currency.

Final note: If you need a less common locale, it is possible that your implementation of Node.js or browser might not have automatically loaded the right library. Never hit that myself as yet but it is possible and there are ways to load additional locales.


This topic was automatically closed after 30 days. New replies are no longer allowed.