當(dāng)前位置:軟件學(xué)堂 > 資訊首頁(yè) > 網(wǎng)絡(luò)編程 > 編程其他 > 截?cái)嘈?shù)點(diǎn)位數(shù)JS代碼怎么寫

截?cái)嘈?shù)點(diǎn)位數(shù)JS代碼怎么寫

2012/11/6 17:18:56作者:佚名來(lái)源:網(wǎng)絡(luò)

移動(dòng)端

【實(shí)例名稱】

截?cái)嘈?shù)點(diǎn)位數(shù)JS代碼怎么寫

【實(shí)例描述】

當(dāng)用戶不知道數(shù)據(jù)庫(kù)中數(shù)據(jù)的小數(shù)位數(shù)時(shí),可通過(guò)程序判斷用戶輸入的數(shù)據(jù),自動(dòng)截取到需要的小數(shù)位數(shù)。本例演示如何自動(dòng)截?cái)嘈?shù)點(diǎn)的位數(shù)。

【實(shí)例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁(yè)-學(xué)無(wú)憂(www.denvermotorcycleaccidentlawyer.com)</title> <script language=javascript> function sts() {     var txt=eval(document.getElementById("Text1").value);  //獲取要截取的數(shù)據(jù)     alert(txt.toFixed(2));                                 //顯示截取后的數(shù)據(jù) } </script> </head> <body>     <input id="Text1" type="text"  value="12345.267514" />     <input id="Button1" type="button" value="截取2位" onclick="sts()" /> </body> </html>

 

 

【運(yùn)行效果】

 截?cái)嘈?shù)點(diǎn)位數(shù)運(yùn)行效果

【難點(diǎn)剖析】

本例的重點(diǎn)是“eval”函數(shù)和“toFixed”方法?!癳val”函數(shù)可以將字符型數(shù)據(jù)轉(zhuǎn)換為數(shù)值型。“toFixed”方法返回一個(gè)字符串類型的數(shù)字,該字符串中小數(shù)點(diǎn)之前必須至少有一位有效數(shù)字,而且其后必須包含參數(shù)中指定位數(shù)的數(shù)字。

【源碼下載】

為了JS代碼的準(zhǔn)確性,請(qǐng)點(diǎn)擊:截?cái)嘈?shù)點(diǎn)位數(shù) 進(jìn)行本實(shí)例源碼下載 

標(biāo)簽: 截?cái)?nbsp; JS代碼