5

我有一些对我来说效果很好的javascript,我只是希望它保留2个小数位,而不是隐藏额外的小数位(如果它是0)。

现在它说:“0.2”,我想说:“0.20”

这是Javascript。谁能告诉我如何实现这一目标?

 $(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();
});
4

1 回答 1

9

您可以使用toFixed函数。它返回一个字符串,但在你的情况下应该没问题:

js> x = 0.2
0.2
js> x.toFixed(2)
0.20
js> 
于 2012-10-15T20:03:39.793 回答