如何将输出限制为2位小数。 [英] How Do I Limit the output to 2 decimals.

查看:73
本文介绍了如何将输出限制为2位小数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。如果输入12/88,你会得到7.3333333333333333

我希望任何除法只有2位小数,但似乎无法找到正确的方法。我想在TextBoxAvgTimeMedRec字段中得到结果。



Here is my code. if you enter 12 / 88 you get 7.3333333333333333
I want any division to be only 2 decimals long but can't seem to find the correct way. I want to have the result in my TextBoxAvgTimeMedRec field.

<script lang='text/javascript'>
  function Calculate()
  {
    if ( (document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value != " ") && (document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value != " ") )
    {
        document.getElementById('<%= TextBoxAvgTimeMedRec.ClientID%>').value = parseFloat(document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value) / parseFloat(document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value);
    }
  }
</script>

推荐答案

此用户的固定功能:



User toFixed function for this:

parseFloat("12.344343").toFixed(2)


你可以使用Math.round或者固定以限制小数位。以下是脚本:



You can either use Math.round or toFixed to limit decimal places. Here is the script:

var a = 12;
var b = 88;
var c = a/b;
alert( Math.round(c * 100) / 100 );
alert(c.toFixed(2));


你可以用< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed> .toFixed() [ ^ ]这里获得所需的输出,并使用通用函数再次重用代码,如:



You can use .toFixed()[^] here to get the desired output and also use a generic function to reuse the code again like:

function Calculate() {
    var textBoxNumPatInt = document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value;
    var textBoxNumMinDoc = document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value;

    if ((textBoxNumPatInt !== "") && (textBoxNumMinDoc !== "")) {
        var newValue = GetDecimalValue(textBoxNumMinDoc) / GetDecimalValue(textBoxNumPatInt);
        document.getElementById('<%= TextBoxAvgTimeMedRec.ClientID%>').value = GetDecimalValue(newValue);
    }
}

function GetDecimalValue(value) {
    return (value ? parseFloat(value).toFixed(2) : 0.00);
}





希望这会有所帮助!



Hope this helps!


这篇关于如何将输出限制为2位小数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆