[英]How to remove digits after decimal using JavaScript?
我在 HTML 網頁中使用數字。 問題是我想要沒有小數的數字。
function copyText() { var mynumber = document.getElementById("field1").value; alert(mynumber); var mytest = parseInt(mynumber); }
Field1: <input type="number" id="field1" value="123.124" /><br /><br /> <button onclick="copyText()">Check Number</button> <p>A function is triggered when the button is clicked. The function copies the text in Field1 to Field2.</p>
假設您只想截斷小數部分(不舍入),這里有一個更短( parseInt()
便宜)的替代parseInt()
或Math.floor()
:
var number = 1.23;
var nodecimals = number | 0; // => 1
使用int
、 float
和string
輸入的bitwise OR 0
行為的更多示例:
10 | 0 // => 10
10.001 | 0 // => 10
10.991 | 0 // => 10
"10" | 0 // => 10
"10.1" | 0 // => 10
"10.9" | 0 // => 10
你應該使用 JavaScript 的parseInt()
var num = 233.256;
console.log(num.toFixed(0));
//output 233
返回字符串:
(.17*parseInt(prescription.values)*parseInt(cost.value)).toFixed(0);
返回整數:
Math.round(.17*parseInt(prescription.values)*parseInt(cost.value));
解析整數時記得使用基數:
parseInt(cost.value, 10)
從數學上講,使用floor
函數最有意義。 這給你一個實數到最大的前一個整數。
ans7 = Math.floor(.17*parseInt(prescription.values)*parseInt(cost.value));
您是否嘗試使用parseInt
獲取價值
嘗試 :
console.log(parseInt(ans7));
~~
運算符是Math.floor()
的更快替代品。
function copyText() { var mynumber = document.getElementById("field1").value; alert(~~mynumber); }
<fieldset> <legend>Field1</legend> <input type="number" id="field1" value="123.124" /> <button onclick="copyText()">Check Number</button> </fieldset>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.