Javascript-只获取所选元素的两个小数

Javascript - Get only two decimals on selected element

本文关键字:两个 小数 获取 元素 Javascript-      更新时间:2023-09-26

我想在这里得到一些帮助。我只需要在增值税字段中输入两位小数。

提前感谢的任何帮助

$('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()返回一个String,如果您想确保结果仍然是一个数字(例如,如果您以后想处理它),只需将其解析为浮点值。

VAT.innerText = parseFloat((selected_value * 0.23).toFixed(2));

更改为selected_value*0.23更改为(selected_vvalue*0.23)。更改为Fixed(2)

$('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).toFixed(2);
  
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>