Neluttu
Neluttu

Reputation: 33

jQuery round number only if decimal is greater than x

So I have these two input[text] fields:

<input type="text" id="CM" size="2" maxlength="5">

and

<input type="text" id="CM2" readonly>

And this jQuery code:

<script type="text/javascript">
        $('#CM').keyup(function(){
        $total = ($('#CM').val() * 3) / 2;
        $('#CM2').val($total);
        });
</script>

It's just a simple math operation and I need it tweaked a bit and I'm stuck.

I need to round up $total variable ONLY IF the first decimal number is greater or equal to 3. Else, round down $total.

So, if $total = 3,3; I need it rounded up to 4. else if $total = 3,2; I need it rounded down to 3.

Can someone help out? Thanks!

Upvotes: 1

Views: 1355

Answers (2)

Thiago Santos
Thiago Santos

Reputation: 111

$('#CM').keyup(function(){
        $total = ($('#CM').val() * 3) / 2;

        if (($total-parseInt($total)) >= 0.3)  {
            $total = parseInt($total) + 1;
        } else {
            $total = parseInt($total);
        }
        $('#CM2').val($total);
 });

if value is greater than .3, parse + 1. If not, just parse.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

Try to use reminder to get the first decimal

$('#CM').keyup(function() {
  var $total = ($('#CM').val() * 3) / 2;
  $('#CM2').val(($total * 10 % 10 <= 3) ? Math.floor($total) : Math.ceil($total));

  //just to display the actual total
  $('#actual').val($total)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="CM" size="2" maxlength="5">
<input type="text" id="CM2" readonly>

<input type="text" id="actual" readonly>

Upvotes: 2

Related Questions