How to display a typescript number with a specific formatting?

Asked

Viewed 38 times

0

I own a property montante in the object below, and I am presenting in the function escreverNaTela():

class Objeto{

  constructor(private montante: number){}

  escreverNaTela(){
    let mensagem = 'R$ ' + this.montante;
    console.log(mensagem);
  }
}

However, when writing on the screen, if the value of montante is an integer the value will not appear with the two decimal places after the comma, as usual. How can I convert the string to that value montante so that it has these 2 decimal places after the comma?

  • 1

    But it’s not just using toLocaleString() ?

  • That’s right, thank you

1 answer

1


Following @Leandrade’s cue, I used the method Number.prototype.toLocaleString:

escreverNaTela(){
  let mensagem = this.montante.toLocaleString('pt-BR', {style: 'currency',currency: 'BRL'});
  console.log(mensagem);
}

If necessary, you can use the option minimumFractionDigits:

escreverNaTela(){
    let mensagem = this.montante.toLocaleString('pt-BR', {minimumFractionDigits: 2});
    console.log(mensagem);
}

Browser other questions tagged

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