Error comparing two strings with float value

Asked

Viewed 584 times

0

Good afternoon!

I am trying to compare numbers with Jquery, they are values with decimals or not. when the value goes up to 999 everything works perfectly, but above this does not work as it should.

Example: value_mo_contract = 510.00

total_mobra_orc_calc = 1000

$(document).ready(function(){
var valor_mo_contrato_s = parseFloat($("#valor_mo_contrato").val()).toFixed(2);
var valor_mobra_s = parseFloat($("#total_mobra_orc_calc").val()).toFixed(2);

  if (valor_mo_contrato_s < valor_mobra_s) {
     $("#valor_unitario_orc_check").text("O Sistema sugere que o Fiscal verifique o valor de Mao de Obra.");
    $("#valor_unitario_orc_check").css({"color": "red"});
  }
});
  • Andre, probably this occurring because your decimal separator should be as a comma and not a point. if you can put what values you are entering in each field. editing your question

  • This with dot, but is there any problem for example if one of the numbers comes without separator? Type A 510.00 compared to 1000

1 answer

5


You are comparing 2 strings using the < operator because Voce is using the method .toFixed(2) after executing the parseFloat

You would need to compare the two values directly as Number and not as string.

One of the possible solutions is to convert again with the parseFloat when making the comparison on if.

$(document).ready(function(){
var valor_mo_contrato_s = parseFloat($("#valor_mo_contrato").val()).toFixed(2);
var valor_mobra_s = parseFloat($("#total_mobra_orc_calc").val()).toFixed(2);

  if (parseFloat(valor_mo_contrato_s) < parseFloat(valor_mobra_s)) {
     $("#valor_unitario_orc_check").text("O Sistema sugere que o Fiscal verifique o valor de Mao de Obra.");
    $("#valor_unitario_orc_check").css({"color": "red"});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="valor_mo_contrato" value="500.3">
<input type="text" id="total_mobra_orc_calc" value="1000">
<div id="valor_unitario_orc_check"></div>

  • Thanks my friend, solved my problem. Strong Hug!

  • I’m glad the answer helped you! ;)

  • @Andremaia If the answer solved your problem mark it as a solution on the left side.

  • Okay Thanks for the help

Browser other questions tagged

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