對於一些小數點后有多位的浮點數,我們可能只需要保留2位,但js沒有提供這樣直接的函數,所以我們得自己寫函數實現這個功能,代碼如下:
function changeTwoDecimal(x)
{
var f_x = parseFloat(x);
if (isNaN(f_x))
{
alert('function:changeTwoDecimal->parameter error');
return false;
}
f_x = Math.round(f_x *100)/100;
return f_x;
}
功能:將浮點數四舍五入,取小數點后2位
用法:changeTwoDecimal(3.1415926) 返回 3.14
changeTwoDecimal(3.1475926) 返回 3.15
js保留2位小數(強制)
對於小數點位數大於2位的,用上面的函數沒問題,但是如果小於2位的,比如:
changeTwoDecimal(3.1),將返回 3.1,如果你一定需要3.10這樣的格式,那么需要下面的這個函數:
function changeTwoDecimal_f(x)
{
var f_x = parseFloat(x);
if (isNaN(f_x))
{
alert('function:changeTwoDecimal->parameter error');
return false;
}
f_x = Math.round(f_x*100)/100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0)
{
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2)
{
s_x += '0';
}
return s_x;
}
功能:將浮點數四舍五入,取小數點后2位,如果不足2位則補0,這個函數返回的是字符串的格式
用法:changeTwoDecimal(3.1415926) 返回 3.14
changeTwoDecimal(3.1) 返回 3.10
另:
parseFloat 方法
返回由字符串轉換得到的浮點數。
parseFloat(numString)
必選項 numString 參數是包含浮點數的字符串。
說明
parseFloat 方法返回與 numString 中保存的數相等的數字表示。如果 numString 的前綴不能解釋為浮點數,則返回 NaN (而不是數字)。
parseFloat("abc")
//
返回 NaN
。
parseFloat("1.2abc")
//
返回 1.2
。
可以用 isNaN 方法檢測 NaN。
示例1:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
<script>
function changetText() {
document.getElementById("txtB").value = document.getElementById("txtA").value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtA" runat="server" onblur="changetText()"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
示例2:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
<script>
//把數值保存3位有效值
function changeThreeDecimal_f(varObj)
{
var x = varObj.value;
var f_x = parseFloat(x);
if (isNaN(f_x))
{
return;
}
f_x = Math.round(f_x*1000)/1000;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0)
{
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 3)
{
s_x += '0';
}
varObj.value = s_x;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtA" runat="server" onblur="changeThreeDecimal_f(this)"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>