嗨,我真的需要您的帮助。

目前,我使用此代码进行自动计算。

但是然后我得到8.749999999999998作为答案。(最好是8.75)
我尝试使用固定为2,但仍然得到相同的答案。

<span name="epr_fctot"  id="epr_fctot" class="medium" size="15">
<script  type="text/javascript">
function fcFunction() {

var fc_airticket =parseFloat(document.getElementById("fc_airticket").value)
var fc_accomodation =parseFloat(document.getElementById("fc_accomodation").value)
var fc_allowance = parseFloat(document.getElementById("fc_allowance").value)
var fc_transport = parseFloat(document.getElementById("fc_transport").value)
var fc_entertainment =parseFloat(document.getElementById("fc_entertainment").value)
var fc_other = parseFloat(document.getElementById("fc_other").value)

var x = parseFloat(fc_airticket) + parseFloat(fc_accomodation)+parseFloat(fc_allowance)+ parseFloat(fc_transport)+parseFloat(fc_entertainment)+ parseFloat(fc_other);

document.getElementById("epr_fctot").innerHTML = x


}
</script>

</span></label></td>

最佳答案

你可以这样尝试
对于字符串-

var twoPlacedFloat = parseFloat(x).toFixed(2);


对于数字,我做了一个函数。

Number.prototype.round = function(num) {
 num= num || 10;
  return parseFloat( this.toFixed(num) );
};


根据您的情况申请-

x.round(2)


编辑

您也可以尝试这个。

Math.round(x * 100) / 100

关于javascript - 转换值int十进制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45925228/

10-15 03:43