How to format result with comma and dot?

Asked

Viewed 1,418 times

2

How do I format the result of a sum with comma and dot.

The Result:

80.50 *  52 = 4189.00

As I intend:

80.50 *  52 = 4,189.00

My JS

function calcular() {
 var valores1 = document.getElementsByClassName('txt1');
 var valores2 = document.getElementsByClassName('txt2');
 var resultados = document.getElementsByClassName('result');

 for (let i = 0; i < valores1.length; ++i) {
     let num1 = parseFloat(valores1[i].value);
     let num2 = parseFloat(valores2[i].value);
     resultados[i].value = (num1 * num2).toFixed(2);
 }
}
  • Have you researched here on [pt.so]? What did you think?

  • the link https://answall.com/questions/55085/como-formatr-um-valor-em-javascript may be useful to you.

  • The result of your question is wrong. rs

  • 80.50 * 52 = 4,186.00

  • Yes, I typed wrong hahaha.

  • I don’t think you’ve been to math class

  • I used the calculator to calculate, for calculating 80.50 * 52 head I would never calculate.

  • then.on that day that you missed, the teacher taught to use the calculation machine kkkk It is always good to choose an answer as accepted, see why here https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-accepta reply/1079#1079

Show 3 more comments

4 answers

3

One simple regular expression solves your problem:

var numero = "4189.00";
numero = numero.replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

Upshot: "4,189.00"

This regular expression works for any number size, with or without decimals (but only up to 3 houses after the point).

  • 1

    Look, +1, but "simple" and "regular expression" in the same sentence is a joke.

  • True, haha! It’s just that I’m already used to regular expressions.

1


resultados[i].value = (((num1 * num2).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ","));

Example:

function calcular(){
    var valores1 = document.getElementsByClassName('txt1');
    var valores2 = document.getElementsByClassName('txt2');
    var resultados = document.getElementsByClassName('result');

    for (let i = 0; i < valores1.length; ++i){
        let num1 = parseFloat(valores1[i].value);
        let num2 = parseFloat(valores2[i].value);
        //resultados[i].value = (num1 * num2).toFixed(2);
        
       resultados[i].value = (((num1 * num2).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    }
}
<input class="txt1" value="80.50" name="opcao1" id="opcao1" type="text">
<input class="txt2" value="52" name="opcao2" id="opcao2" type="text">
<input class="result" value="" name="opcao3" id="opcao3" type="text" onclick="calcular()" placeholder="Clique aqui para calcular">

The idea is to match recursively - with the flag g (global) - doing a positive Lookahead (?=(\d{3})+(?!\d)) - a sequence of 3 digits (\d{3}) as long as there is no digit on the right (?!\d) of this sequence - and that it is not start or end of the chain \B

Lookahead is a way of marrying strings that have a certain ending or not. It is used (?=...) for the positive, that is, ending with, and (?!...) for the negative, that is, it does not end with the negative.

A simple example would be the search for Rafael followed by Ferreira. If there was Rafael or Rafael Outracoisa, he would not marry. /Rafael(?= Ferreira)/

On the contrary, in this example, I would only marry Rafael or Rafael Outracoisa, but I would not marry Rafael Ferreira: /Rafael(?! Ferreira)

1

There is a method called toLocaleString(). This method returns a string with a language-sensitive representation of that number.

According to the exit documentation default of the method is American standard

var number = 3500;
console.log(number.toLocaleString()) //3,500

The strange thing is that when testing this is not what happens, applying the standard // 3.500. There is the German standard that formats monetary values according to Brazil. To this add the parameter de-DE to the method

var number = 123456.789;
console.log(number.toLocaleString('de-DE', { maximumFractionDigits: 2 }))
//123.456,79

1

I use the plugin maskMoney

Then just customize your field with jQuery.

 $(document).ready(function () {
      $("#valor").maskMoney({ thousands: '', decimal: ',', allowZero: true });
  });

HTML

<div class="form-group" id="div_valor">
                        <div class="input-group">
                            <div class="input-group-addon">
                                @Html.LabelFor(model => model.valor, new { @class = "control-label col-md-2" })
                            </div>
                            @Html.TextBoxFor(model => model.valor, new { @class = "form-control" })
                        </div>
                    </div>

Browser other questions tagged

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