coce
coce

Reputation: 49

How can I round the value to 1 decimal?

I have a set of radio buttons in different fieldsets. I'm able to get the value of the radio buttons and divide that number however I'm not sure how to round it.

I would like to round the value of Total Score to one decimal.

HTML

<fieldset>
  <input class="calc" type="radio" id="star15" name="rating2" value="5" /><label for="star15">5 stars</label>
  <input class="calc" type="radio" id="star14" name="rating2" value="4" /><label for="star14" class="m-r-48">4 stars</label>
  <input class="calc" type="radio" id="star13" name="rating2" value="3" /><label for="star13" class="m-r-48">3 stars</label>
  <input class="calc" type="radio" id="star12" name="rating2" value="2" /><label for="star12" class="m-r-48">2 stars</label>
  <input class="calc" type="radio" id="star11" name="rating2" value="1" /><label for="star11" class="m-r-48">1 star</label>
</fieldset>

<fieldset>
  <input class="calc" type="radio" id="star20" name="rating3" value="5" /><label for="star20">5 stars</label>
  <input class="calc" type="radio" id="star19" name="rating3" value="4" /><label for="star19" class="m-r-48">4 stars</label>
  <input class="calc" type="radio" id="star18" name="rating3" value="3" /><label for="star18" class="m-r-48">3 stars</label>
  <input class="calc" type="radio" id="star17" name="rating3" value="2" /><label for="star17" class="m-r-48">2 stars</label>
  <input class="calc" type="radio" id="star16" name="rating3" value="1" /><label for="star16" class="m-r-48">1 star</label>
</fieldset>

<fieldset>
  <input class="calc" type="radio" id="star25" name="rating4" value="5" /><label for="star25">5 stars</label>
  <input class="calc" type="radio" id="star24" name="rating4" value="4" /><label for="star24" class="m-r-48">4 stars</label>
  <input class="calc" type="radio" id="star23" name="rating4" value="3" /><label for="star23" class="m-r-48">3 stars</label>
  <input class="calc" type="radio" id="star22" name="rating4" value="2" /><label for="star22" class="m-r-48">2 stars</label>
  <input class="calc" type="radio" id="star21" name="rating4" value="1" /><label for="star21" class="m-r-48">1 star</label>
</fieldset>

Total Score:
<input type="text" name="sum" />

JS

function calcscore(){
    var score = 0;
    $(".calc:checked").each(function(){
        score+=parseInt($(this).val(),10);
    });
    $("input[name=sum]").val(score / 8)
}
$().ready(function(){
    $(".calc").change(function(){
        calcscore()
    });
});

Here's a fiddle: https://jsfiddle.net/b4y7adg3/1/

Upvotes: 1

Views: 1224

Answers (1)

kzhao14
kzhao14

Reputation: 2630

You can round the value multiplied by 10, then divide by 10:

var value = Math.round(number / 8 * 10) / 10;

See your fiddle

You can alternatively use .toFixed(1); however, this will force a decimal, so that a value of 6, for example, becomes 6.0.

Upvotes: 2

Related Questions