Pregunta

In the following question/answer:

Configure Cart Price Update

The response gives an example that provides a working method - however, I had to change it to allow for floating point math.

The problem now is that I cannot convert the answer to 2 decimal places. The answer is sometimes given with 15! decimal places.

Here is my modified java code from the original - how do I get it to output to 2 decimals?

<script type="text/javascript">
$(document).ready(function(){
    var basePrice = 39.95;
    $("#baseCost").text(basePrice);
    $("#sumTotal").text(basePrice);
});

function calculateTotals(){
    var basePrice = parseFloat($("#baseCost").text(), 10);
    var upgradePrice = 0.00;
    $("#options select").each(function(){
        var optionVal = $(this).val();
        upgradePrice += parseFloat(optionVal.substr(optionVal.indexOf("_") + 1, optionVal.length - 1), 10);
    });
    $("#upgradeCost").text(upgradePrice);   
    $("#sumTotal").text(basePrice + upgradePrice);
}
</script>
¿Fue útil?

Solución

Every number variable has a method called toFixed.

var sumTotal = basePrice + upgradePrice;
$("#sumTotal").text(sumTotal.toFixed(2));

Edit: Changed answer to something more specific.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top