Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ceil with 2 decimal places instead of 1

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();
});
like image 866
ihateartists Avatar asked Oct 15 '12 19:10

ihateartists


People also ask

How do I force two decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you only get to two decimal places?

If we want to round 4.732 to 2 decimal places, it will either round to 4.73 or 4.74. 4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74).


1 Answers

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> 
like image 125
Xavier Holt Avatar answered Nov 02 '22 07:11

Xavier Holt