Format currency to select from JSON

Asked

Viewed 182 times

0

I have this select that loads the options coming from a JSON.

I would like to show the values that are placed in select in Real format (999,99) but even using the response functions of this question the values have no effect or are shown in the format 999.,00.

function loadItens(){
  $.getJSON("https://api.myjson.com/bins/10hz22",function(data){
    $.each(data, function(key, val){
      $("#select-iten").append("<option value='"+key+"'>"+
      val.nome+" ("+ val.preco +")</option>");
    });
  });
}

loadItens();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-iten">
  <option>Selecione</option>
</select>

How can I solve this problem?

1 answer

2


You can try as shown below, basically the conversion was made to float and then used the function toLocaleString

function loadItens(){
  $.getJSON("https://api.myjson.com/bins/10hz22",function(data){
    $.each(data, function(key, val){
      $("#select-iten").append("<option value='"+key+"'>"+
      val.nome+" ("+ parseFloat(val.preco).toLocaleString('pt-br',{style: 'decimal', minimumFractionDigits:2}) +")</option>");
    });
  });
}

loadItens();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-iten">
  <option>Selecione</option>
</select>

  • That’s weird, I tested it and it hadn’t worked.

  • Now I have another problem, I need you to show 50,00 when you have no pennies and don’t show the $ , can help me?

  • You’re not seeing it that way in the example R$ 50,00 ?

  • I am, but when I take back the option {style: 'currency', currency: 'BRL'} appears 50. In this specific case I don’t need the R$

  • You don’t want me to show you R$ ?

  • That’s right, I don’t want you to show R$.

  • 1

    Just put the option {minimumFractionDigits: 2}. Thanks friend.

Show 2 more comments

Browser other questions tagged

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