如何在输入上转换为小数点后 2 位
How can I convert to 2 decimal places on inputs?
我怎样才能做一个脚本来乘以 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
请有人可以帮助我吗?
我将不胜感激
您可以使用.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;
}
您可以使用
number.toFixed(2)
原型。
编辑:这将返回 Costo 的1.20
,而不是1.2
。如果您希望四舍五入到小数点后 2 位,您可以使用 tak3r 提供的Math.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
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- 如何在Javascript中将JSon对象转换为数组
- 使用JS将数组转换为json对象
- 如何使用json将对象列表从java转换为javascript
- 偶尔结结巴巴地说“;堆叠的”;translate()上的转换(v4.0.0-alpha40)
- 为什么在单独的函数中应用时转换会闪烁/断断续续(D3)
- 在Javascript中转换对象数组
- 将数字转换为一定数量的硬币
- 将纯文本URL转换为可单击链接
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- 如何将TypeScript对象转换为普通对象
- 检测个位数整数时正在转换毫秒
- 将浮点转换为至少有一个小数点的字符串(javascript)
- 如何在输入上转换为小数点后 2 位
- 将 JavaScript 数字转换为小数点后两位
- 在jQuery中将值转换为小数点后2位
- 角度滤波器,用于将数字转换为具有两个小数点的数十亿
- 在转换期间将数字格式化为小数点后一位?(d3.js)
- 我正在尝试将数字转换为货币,并添加带有2个小数点的数字