0

I have a number and I want to put into money format, brasilian money. I usually use format like this:

that.totalSales = numeral(that.totalSales).format("$ 0,0.00");

but that returns a string and I want it to return a number so I can build a chart with chart.js. Itried to use toLocaleString('pt-BR'), but a value that was to return 9.990.220,32, that returns 9.99.

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
  • Does this answer your question? [How to format numbers as currency string?](https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-string) – DCR Apr 06 '20 at 20:48
  • Anything starting with a currency sign (e.g. "$") will be a string, and can not (easily) be coerced into a number. Why not just use the value of `that.totalSales` *before* you alter it, which is apparently a number? – kmoser Apr 06 '20 at 21:02
  • it is a number, but a really big number kkkkk, it's 11786775.13, and I need to show as money like 11.786.775,13 – Gustavo Oliveira Apr 06 '20 at 21:05

2 Answers2

0

Here is a function which does that, it can probably be written much shorter and better but this is what I came up with:

const formatNumber = (number, decimals = 2, floatSeparator = '.', separator = ',') => {
    let stringified = number.toString();
    let [ decimal, float ] = stringified.split('.');
    let result = "";
    if(decimal.length > 3) {
        decimal = decimal.split("").reverse();
        for(let i = 0; i < decimal.length; i++) {
            result += decimal[i];
            if((i + 1)%3 === 0 && i !== decimal.length - 1) {
                result += separator;
            }
        }
    }
    result = result.split("").reverse().join("");
    if(float) {
        result += floatSeparator;
        if(float.length >= decimals) {
            for(let i = 0; i < decimals; i++) {
                result += float[i];
            }
        }
        else {
            for(let i = 0; i < decimals; i++) {
                if(i < float.length) {
                    result += float[i];
                }
                else {
                    result += '0';
                }
            }
        }
    }
    return result;
}

let n1 = 1000;
let n2 = 1000.5;

console.log(formatNumber(n1)); // 1,000
console.log(formatNumber(n2)); // 1,000.50
TZiebura
  • 494
  • 3
  • 15
0

You can simply use the number-to-currency package on npm which convert number to currency string with one command.

How to use:

install first through npm or yarn: npm install number-to-currency

const formatter = require("number-to-currency")

formatter(2000) -> 2,000
wavefly
  • 147
  • 2
  • 5