我想在这里得到一些帮助。 我只需要在增值税字段中保留两位小数。
预先感谢您的帮助
$('select').change(function() {
var selected_value = $('#sel option:selected').val();
var no_VAT = document.getElementById('no_VAT');
no_VAT.innerText = selected_value;
var VAT = document.getElementById('VAT');
VAT.innerText = selected_value * 0.23;
var with_VAT = document.getElementById('with_VAT');
with_VAT.innerText = selected_value * 1.23 ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selector" id="sel">
<option value="10">2</option>
<option value="12">3</option>
<option value="18">6</option>
</select>
<p id="no_VAT"></p>
<p id="VAT"></p>
<p id="with_VAT"></p>
最佳答案
您可以使用 toFixed() 将数字结果格式化为小数点后 2 位:
var VAT = document.getElementById('VAT');
VAT.innerText = (selected_value * 0.23).toFixed(2);
^^^^^^^^^^
由于 fixedTo()
返回一个字符串,如果您想确保结果仍然是一个数字(例如,如果您想稍后使用它),只需将其解析为 float 即可。
VAT.innerText = parseFloat((selected_value * 0.23).toFixed(2));
关于Javascript - 在所选元素上仅获取两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120190/