6

I have a bit of javascript that's working well for me, I'd just like it to keep 2 decimal places instead of hiding the extra decimal place if its 0.

Right now it says: "0.2" and I'd like it to say: "0.20"

Here's the Javascript. Can anyone please show me how to achieve this?

 $(function() {

var valueMultiplier = <?php echo $savingsVar; ?>;

function updateAmounts() {

    // valueMultiplier = savings
    // value1 = how often do you change your printer cartridges?
    // value2 = how frequently you change them

    var value1 = $('#slider').slider('value');

    var value2 = $('#slidertwo').slider('value');

    var value3 = ((valueMultiplier * value1) * value2);
    var value3 = (Math.ceil(value3 * 10) / 10);

    // add month to it
    if(value1==1){
        value1 = value1 + ' month';
    }else{
        value1 = value1 + ' months';
    }

    value2 = value2 + ' months';

    $('#amount').val(value1);

    $('#amounttwo').val(value2);

    $('#amountthree').val(value1 + value2);

    $('#amountfour').val(value3);

    $('#amountfive').val(value3);

}

$('#slider').slider({value: 1, min: 1, max: 12, step: 1, stop: function(event, ui) {
    updateAmounts();
}});
$('#slidertwo').slider({value: 1, min: 3, max: 36, step: 3, stop: function(event, ui) {
    updateAmounts();
}});

$('#price').val("$" + valueMultiplier);

updateAmounts();
});
ihateartists
  • 328
  • 4
  • 17
  • 1
    I think what you are looking for is `parseFloat(num).toFixed(2)` https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed – Selvakumar Arumugam Oct 15 '12 at 20:03

1 Answers1

8

You can use the toFixed function. It returns a string, but that should be okay in your case:

js> x = 0.2
0.2
js> x.toFixed(2)
0.20
js> 
Xavier Holt
  • 14,471
  • 4
  • 43
  • 56
  • Where would that go in my code? After the ceil function or in place of the ceil function or...? – ihateartists Oct 15 '12 at 22:05
  • 1
    @user1703674 - It actually has nothing to do with the math (0.2 = 0.20 = 0.200 and so on, and they're all represented the same, internally). It's a _display_ function. It returns a string because that's the only way to ensure it has the correct number of decimal places. Call it just before you put that value on the page: `$('#foo').val(value3.tofixed(2));` or `value3 = value3.toFixed(2); $('#foo').val(value3);` – Xavier Holt Oct 16 '12 at 10:02