1

I have developed a code in which adds values and at the end subtracts the smallest value based on the items you select in a form. The code for the most part works great however I'm running into a problem when it displays the total. When my value is 7.25 it will work fine but if its a whole number it will only display 5. I would like it to display 5.00. Any advice?

<script language="JavaScript"> 

// All selected prices are stored on a array
var prices = [];

// A function to remove a item from an array
function remove(array, item) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i] == item) {
            array.splice(i, 1);
            return true;
        }
    }
    return false;
}

function calculateSectedDues(checkbox, amount) {
    // We add or remove the price as necesary

    if (checkbox.checked) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    // We sum all the prices
    var total = 0;
    for (var i = 0, len = prices.length; i < len; i++)
        total += prices[i];

    // We get the lower one
    var min = Math.min.apply(Math, prices);

    if(min == Infinity) { min = 0; }

    // And substract it
    total -= min;

    // Please, don't access the DOM elements this way, use document.getElementById instead
    document.grad_enroll_form.total.value = total;

}


</script>
  • 1
    possible duplicate of [JavaScript: formatting number with exactly two decimals](http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals) – Matt Ball Apr 16 '13 at 21:46
  • You'll need a jQuery plugin to do this. Adding a decimal point is by no means trivial and requires a large number formatting library to be added. – adeneo Apr 16 '13 at 21:49
  • @Alfie_Fitz - that was a joke, did you try the answer below? It's that easy! – adeneo Apr 16 '13 at 21:52
  • @Alfie_Fitz you're saying this _is not_ a duplicate of the linked question? How? – Matt Ball Apr 16 '13 at 21:56

2 Answers2

4

You can use JS's toFixed() method:

var min = 2;
min.toFixed(2); // returns 2.00
Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30
0
if(parseInt(total) == total){
    total += ".00";
}

or short if notation:

total = parseInt(total) == total ? total + ".00" : total
Ivan Vetrov
  • 61
  • 2
  • 7