0

I have a code fast and quiet, but results in some calculations are formatted very large, including, the value obtained does not enter the calculation. How to do this see the right result?

I would like the result of the calculation (3 * 2215.40) was 3 646.20 and non 3.6450000000000005.

How?

Code - http://jsfiddle.net/bruno_aw/M7JZu/

$(".calc_cub").on("keyup", ".qtd", function(){
    var valorCub = $("#CUB").text();        
    var number = parseFloat(valorCub);  
    var qtd = +$(this).val();
    $(".total").text(number * qtd).val().toFixed(2);
});
bda.awk
  • 29
  • 6

3 Answers3

1

You need to first get the number out of the text. You are also calling .val() after you set the text on .total - which all you need to really do is $(".total").text((number * qtd).toFixed(2));

$(".calc_cub").on("keyup", ".qtd", function () {
    var valorCub = $("#CUB").text().split(' '); // returns ["Valor", "CUB", "R$", "1,215.40"]
    var number = parseFloat(valorCub[valorCub.length - 1].replace(',','')); // get last one in array and remove comma
    var qtd = +$(this).val();
    $(".total").text((number * qtd).toFixed(2));
});

http://jsfiddle.net/GMjjc/

wirey00
  • 32,479
  • 7
  • 49
  • 64
  • OW Man!! I tried several times to use the replace and format, plus the slit did not know. Congratulations and thank you. perfect @wirey Thanks! – bda.awk Apr 17 '13 at 18:47
  • Your welcome :) I didn't know if you had a typo in your html or not but I changed it to from `1.215,40` to `1,215.40` – wirey00 Apr 17 '13 at 19:45
0

Try this change:

$(".total").text((number * qtd).toFixed(2));

Note that in your fiddle the CUB div has text and digits. parseFloat() works when the number is at the front of the string. So you will need to arrange things so the number is isolated. You can do it like this:

<div>Some text is here <span id="CUB">1234.50</span></div>
Lee Meador
  • 12,221
  • 1
  • 29
  • 38
  • Exactly, but could not catch the value excluding the "," number. :( – bda.awk Apr 17 '13 at 18:34
  • Ok! Got the whole problem is the "." This value is the client that uses a table in google docs DataTables. 'll To have to ask take the ",". Thank you Lee Meador, have my gratitude. – bda.awk Apr 17 '13 at 18:41
  • You might read this: http://stackoverflow.com/questions/2085275/what-is-the-decimal-separator-symbol-in-javascript as it discusses the use of international number formatting differences and dealing with them for parseFloat(). – Lee Meador Apr 17 '13 at 18:46
0

You mixed up the string of the text block and the separators for the float. Try this;

http://jsfiddle.net/M7JZu/8/

JavaScript

$(".calc_cub").on("keyup", ".qtd", function () {
    var valorCub = $("#CUB").text();
    valorCub = parseFloat(valorCub.split('$ ')[1].replace('.', '').replace(',', '.'));
    var qtd = $(this).val();
    $(".total").text(valorCub * qtd);
});

For output-sakes, you can convert the . back to a , (comma) again on output.