How to show a separate number per point every 3 houses?

Asked

Viewed 2,780 times

5

How can I format values this way: 1.000 or 150.000 or 42.000 ?

My code is this:

var f02 = 42000;
console.log(parseInt(f02));

I need the variable formatting f02 stay that way: 42.000, and when the number is larger the format adapts, example: 150.000 or 1.000.000

  • You want a separator. It’s not to turn an entire number into real, right?

  • uses the .toLocaleString()

  • That @jbueno, a tab...

  • You will need to present this figure as string. A whole will not allow you to do this.

2 answers

6


One option is the method Number.toLocaleString:

function formatarValor(valor) {
    return valor.toLocaleString('pt-BR');
}

console.log(formatarValor(42000));
console.log(formatarValor(150000));
console.log(formatarValor(1000000));

Using the locale pt-BR, the numbers will be formatted as you want, with ., if you want to use ,, use another locale, for example: en-US.

If you need to display the fractional part, use the parameter minimumFractionDigits followed by the minimum number of digits:

function formatarValor(valor) {
    return valor.toLocaleString('pt-BR', { minimumFractionDigits: 2 } );
}

-2

Follow simple example to put . every three digits and at the end put a comma:

#!/bin/bash

if [ -f "${1}" ]
then
   echo -e "Sintaxe : $0 [ number ]\n"
   exit 1
else
   valor="$1"
fi

     num="`echo "${valor}" | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'`"
     num="`echo ${num} | sed 's:,:.:g'`"
qtde_cps="`echo ${num} | sed 's:\.:\n:g' | wc -l`"
     ult="`expr ${qtde_cps} - 1`"
  inicio="`echo ${num} | cut -d\. -f1-${ult}`"
   final="`echo ${num} | cut -d\. -f${qtde_cps}`"

echo "${num}"
echo -e "${inicio},${final}\n"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.