gpt4 book ai didi

javascript - 如何将输入转换为小数点后两位?

转载 作者:行者123 更新时间:2023-11-29 18:19:56 25 4
gpt4 key购买 nike

我如何编写一个脚本来乘以 2 个输入并对结果求和我的问题是:"我怎样才能在每个输入上放置 2 位小数?

 soles * cost      = subtotal
subtotal + dolares = total

这是我的 View 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

有人可以帮我吗?

我会感谢帮助

最佳答案

您可以使用 .toFixed(2) 或数学上的 Math.floor(number * 100)/100 -> 它们可以互换,但 .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;
}

关于javascript - 如何将输入转换为小数点后两位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19711911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com