2016-10-17 61 views
-1

我的脚本显示小数工作正常,但有时结果是一样100.6456489764,但我想,而不是显示像100.64或只是100,但我不明白这里怎么解决这个问题是我的代码位怎么就不能在这

希望得到你的帮助,并输入该

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xml:lang="en-CA" lang="en-CA" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script language="Javascript"> 
function dosum() 
{ 
    var TD = document.temps.OD.value /document.temps.PV.value *100; 
    var MLTV = document.temps.MA.value /document.temps.PV.value *100 
    document.temps.LTV.value = TD + MLTV 
}     
</script> 
<script type="text/javascript" language="javascript"> 
function display_amount(amount) 
{ 
    var currency = '$'; 

    if(isNumeric(amount)) 
    { 
     if(amount < 0) 
      return '-' + currency + Math.abs(Math.round(amount,2)); 
     else 
      return currency + Math.round(amount, 2); 
    } 
    else 
     return amount; 

} 
</script> 
<title>LTV</title> 
</head> 
<body> 
<FORM NAME="temps"> 
<TABLE bgcolor="#CCCCCC" cellspacing="0" cellpadding="10" width="350"> 
    <TR><TD WIDTH=153 bgcolor="blue"> 
    <font color="yellow"><b>Property Value:</b></font></TD> 
    <TD WIDTH=153 bgcolor="#0fcf00"> 
    <p style="margin-top: 0; margin-bottom: 0"> 
    $<INPUT TYPE="TEXT" NAME="PV" onChange="dosum()" SIZE="8" VALUE=""></p></TD></TR> 
    <TR><TD WIDTH=153 bgcolor="green"> 
    <font color="white"><b>Mortgage Balance:</b></font></TD> 
    <TD WIDTH=153 bgcolor="red"> 
    $<INPUT NAME="MA" onChange="dosum()" SIZE="8" VALUE=""></TD></TR> 
    <TR><TD WIDTH=153 bgcolor="#ddd000"> 
    <font color="green"><b>Additional Debts:</b></font></TD> 
    <TD WIDTH=153 bgcolor="orange"> 
    $<INPUT NAME="OD" onChange="dosum()" SIZE="8" VALUE=""></TD></TR> 
    <TR><TD WIDTH=153 bgcolor="#333000"> <b><font color="#ffffff"> 
    <INPUT TYPE="NUMBER" NAME="LTV" SIZE="10" readonly>%</font></b></TD> 
    <TD WIDTH=153 bgcolor="#333000"> 
    <INPUT TYPE="submit" VALUE="Calculate"></div></TD> 
    </TR> 
    </TABLE> 
    </FORM> 

</body> 
</html> 

感谢提前

+0

所以,'font'元素已经被废弃了很长一段时间......除此之外,看['toFixed'](HTTPS ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)。 –

+2

类似问题:http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript – roger

回答

1

使用.toFixed(2)的值四舍五入到2个位数。

function dosum() { 
    var TD = document.temps.OD.value/document.temps.PV.value * 100; 
    var MLTV = document.temps.MA.value/document.temps.PV.value * 100 
    document.temps.LTV.value = (TD + MLTV).toFixed(2); 
} 
1

使用

Math.round(num * 100)/100 

或者像这样

var discount = (price/listprice).toFixed(2); 
0

对于2位精度使用toFixed()

function dosum() 
{ 
    var TD = document.temps.OD.value /document.temps.PV.value *100; 
    var MLTV = document.temps.MA.value /document.temps.PV.value *100 
    document.temps.LTV.value = (TD + MLTV).toFixed(2); 
}  
+0

谢谢soo –