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();
});
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.
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 %.
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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With