Jquery calculation of centimeters with coin result

Asked

Viewed 331 times

1

I am breaking my head to try to make the code below understand that the value of DIV should be respected the comma (Ex.: 1,20cm) in which would be:

div1(in centimetres) X div2(in centimetres) = RESULTADO1

RESULTADO1 X 140(square metre value) = VALUE IN R CURRENCY$

I can’t see the error no matter how lay...

JSFIDDLE

*EDITED

I adapted to my need but still Jquery does not recognize the unit of measure in centimeters...

Place: Height = 1.90 He disregards ".90"

If I put: Height = 190 It gives an exorbitant result

JSFIDDLE

  • Why don’t you use parseFloat(suaStringAqui).toFixed(2)?

3 answers

0

var test = 'R$ 1.700,90';


function getMoney( str )
{
        return parseInt( str.replace(/[\D]+/g,'') );
}
function formatReal( int )
{
        var tmp = int+'';
        tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
        if( tmp.length > 6 )
                tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

        return tmp;
}


var int = getMoney( test );
//alert( int );

document.getElementById('resultado1').innerHTML = formatReal( 1000 );
document.getElementById('resultado2').innerHTML = formatReal( 19990020 );
document.getElementById('resultado3').innerHTML = formatReal( 12006 );
document.getElementById('resultado4').innerHTML = formatReal( 120090 );
document.getElementById('resultado5').innerHTML = formatReal( int );
<div id="resultado1"></div>
<div id="resultado2"></div>
<div id="resultado3"></div>
<div id="resultado4"></div>
<div id="resultado5"></div>

Edit #1:

Alter parseint for parseFloat

var sum = $('.larg').text(); 
      var sum2 = $('.alt').text();
      var sum3 = $('.metro').text();

        if(sum == "") sum = 0;
        if(sum2 == "") sum2 = 0;
        if(sum3 == "") sum3 = 0;

        var resultado   = parseFloat(sum) * parseFloat(sum2) * parseFloat(sum3);

function getMoney( str )
{
        return parseInt( str.replace(/[\D]+/g,'') );
}
function formatReal( int )
{
        var tmp = int+'';
        tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
        if( tmp.length > 6 )
                tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

        return tmp;
}

document.getElementById('resu').innerHTML = formatReal( resultado );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
largura = <div class="larg">0.70</div><!-- EM Centimetros-->
Altura = <div class="alt">1.20</div><!-- EM Centimetros-->
Metro = <div class="metro">140</div><!-- valor em moeda do Metro quadrado-->

TOTAL = <div id="resu">0</div> <!-- Resultado em moeda-->

  • I found your proposal interesting but the sacrifice is to make the jquery recognize the unit of measurement in centimeters... Height = <div class="alt">1,90</div> it does not recognize this measure

  • change to 1.90

  • with semicolon he does not recognize: https://jsfiddle.net/leoknd/z8d7ot3k/

  • What is the result that is to give ?

  • The calculation should be in square meter, that is: 1.20 (one meter and 20cm) X 0.70 (70 centimeters) X 140 (140 reais) = R$ 117.60

  • SHOW! I am very lay still, thank you so much for teaching me to "fish"

  • Hello Wéllingthon! Can you explain what was wrong with the text question as well? So the answer will become more useful to those who come next with the same problem and want to learn.

Show 2 more comments

0

I assume that my answer is 50% of the question: I could not apply masks. But I have some things to tell you:

  1. It is not good to add everything in divs how you did ! Use inputs is what they serve, mainly for data processing that is your case.
  2. The data taken from div came in the form of string with comma, and you would hardly be able to do anything with it, use "."(dot) to calculate with decimal numbers. I created inputsof the kind number decimal so the value is already formatted.
  3. You were trying to give a parseInt a decimal number, until then ok, but hardly you would arrive at the expected result because you were "rounding up" everything. You should use parseFloat as in Mr Wellingthon’s reply.

These are some observations that I hope you and other users can read as they are very important.

Follow the code with the calculation and the correct values, just missing the mask, I tried to apply the Jquery Markmoney but without success. If someone succeeds, feel free to edit.

Reply in progress, I will be editing later with the rest of the information and mask.

$(document).ready( function() {
        
       $("#calc-buton").click(function() { 
        var sum = $('#largura').val();
        var sum2 = $('#altura').val();
        var sum3 = $('#valorMQuadrado').val();

        if (sum == "") sum = 0;
        if (sum2 == "") sum2 = 0;
        if (sum3 == "") sum3 = 0;

        var resultado = (sum * sum2) * sum3;
        $('#total').val(resultado);     
        
        
  });
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/dist/jquery.mask.min.js"></script>
<script>

</script>

<table>
  <tr>
    <td>Largura:</td>
    <td><input type='number' id='largura' step='0.01' value='2.5' /> </td>
  </tr>

  <tr>
    <td>Altura:</td>
    <td><input type='number' id='altura' step='0.01' value='2.1' /> </td>
  </tr>

  <tr>
    <td>Valor metro²:</td>
    <td><input type='number' id='valorMQuadrado' step='0.01' value='1' /> </td>
  </tr>
  <tr>
    <td>Total:</td>
    <td><input type='text' id='total'  readonly /> </td>
  </tr>

  <tr>
    <td colspan='2'><input type='button' id='calc-buton' value='calcular'></td>
  </tr>
</table>

  • Thank you Xara... The use of div was due to the only solution found so that it was possible to change a result of a return that had to a wordpress post so that then could update the data... Was it a scam? Yes! rsrs, but for a layman that I am... was the only solution ... thanks for the tips

  • Of nothing ;) gambiarra the vezs ends up being necessary even, but beware eim, use them wisely kkk

0


You already have an accepted answer, but I think the problem can be solved more effectively.

Ideas are:

  • creates an array ['.larg', '.alt', '.metro'] with the values multiplying and running it in a changing reducer , for . because Javascript uses dot as decimal separator
  • uses the toLocaleString to reformat the number (I talked about it here)

Suggestion:

var res = ['.larg', '.alt', '.metro'].reduce(function(sum, sel) {
  var nr = $(sel).text().replace(/\./g, '').replace(/,/g, '.');
  return sum * Number(nr);
}, 1).toLocaleString(undefined, {
  minimumFractionDigits: 2
});
$('.resu').text("R$ " + res);
label div {display: inline;}
label {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>largura = <div class="larg">0,70</div></label>
<label>Altura = <div class="alt">1,20</div></label>
<label>Metro = <div class="metro">140</div></label>
<label>TOTAL = <div class="resu">0</div></label>

  • 1

    It fell like a glove... It simplified a lot and I learned how to work with arrays decently

Browser other questions tagged

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