简体   繁体   中英

How to round subtracted values to two decimal places?

I have two values one having two decimal places. I would like the result of the subtracted values to always display two decimal places only. As you can see form the jsfiddle the two numbers in the example display an answer of more than two decimal places. How to I get the answer only two decimal places?

jsfiddle: http://jsfiddle.net/e23wfpj7/

HTML

<div class="numb-one">34.56</div>
<div class="numb-two">10</div>
<div class="click">click</div>
<div class="total"></div>

jQuery

$('.click').on('click', function(){
    var numbOne = $('.numb-one').text();
    var numbTwo = $('.numb-two').text();
    var subtract = numbOne - numbTwo;

    $('.total').html('Total: '+subtract);

});

Simple uses .toFixed(2) on the

var subtract = (numbOne - numbTwo).toFixed(2);

More info here

LiveDemo

小提琴

$('.total').html('Total: ' + Math.round(subtract * 100) / 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM