如何在输入上转换为2位小数?

时间:2013-10-31 16:30:33

标签: javascript

我怎么能用一个脚本来乘以2个输入并求和结果我的问题是: “我怎样才能在每个输入上加上2位小数?

 soles * cost      = subtotal
 subtotal + dolares = total  

这是我的观点html

   <label>Sum Soles :</label>
   <input id="soles" value="2233.3234333" /> 

   <label>Sum Dolars :</label>
   <input id="dolars" value="3244.3566" />

   <br/><br/>
   <label>Cost of Dolar</label>
   <input type="text" id="cost" maxlength="5" onchange="doMath();" />

   <label>Total Soles to Dolars</label>
   <input id="subtotal" readonly="readonly" />

   <br/><br/>  
   <label>SUM TOTAL</label>
   <input id="total" readonly="readonly" />  

这是我的剧本

<script type="text/javascript">
function doMath()
{
    // Capture the entered values of two input boxes
    var soles = document.getElementById('soles').value;
    var cost = document.getElementById('cost').value;
    var dolares=document.getElementById('dolars').value;

    // Add them together and display
    var subtotal = parseFloat(soles) * parseFloat(cost);
    document.getElementById('subtotal').value = subtotal;

    var total = parseFloat(subtotal) + parseFloat(dolars);
    document.getElementById('total').value = total;
}
</script>

我期待结果

Sum Soles : 2233.32
Sum Dolars 3244.36
Cost  : 1.2
Total Soles to dolars = 2679,98
Total :5924,34

请有人帮我这个吗?

我将很感激帮助

2 个答案:

答案 0 :(得分:2)

您可以使用number.toFixed(2)原型。

修改:这将为Costo返回1.20而不是1.2。如果您希望舍入为2位小数,则可以使用tak3r providedMath.round方法。

这是一个做同样事情的原型:

Number.prototype.roundToDecimals = function(decimals) {
    decimals = decimals || 0;
    var pow = Math.pow(10, decimals);
    return Math.round(this * pow) / pow;
};

> (1.234567).roundToDecimals(2); 
1.23

> (1.2).roundToDecimals(2); 
1.2

答案 1 :(得分:2)

您可以使用.toFixed(2)或数学Math.floor(number * 100) / 100 - &gt;它们是可以互换的,但是.toFixed()返回一个字符串,所以请记住

function doMath()
{
    // Capture the entered values of two input boxes
    var soles = document.getElementById('soles').value;
    var costo = document.getElementById('costo').value;
    var dolares=document.getElementById('dolares').value;

    // Add them together and display
    var subtotal = Math.floor(parseFloat(soles) * 100) / 100 * Math.floor(parseFloat(costo) * 100) / 100;
    document.getElementById('subtotal').value = subtotal.toFixed(2);

    var total = parseFloat(subtotal) + parseFloat(dolares);
    document.getElementById('total').value = total;
}