简体   繁体   中英

How to remove digits after decimal using JavaScript?

I am using numeric in an HTML web page. The problem is that I want numbers without decimals.

 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>

Assuming you just want to truncate the decimal part (no rounding), here's a shorter (and less expensive) alternative to parseInt() or Math.floor() :

var number = 1.23;
var nodecimals = number | 0; // => 1

Further examples for the bitwise OR 0 behavior with int , float and string input:

10     | 0 // => 10
10.001 | 0 // => 10
10.991 | 0 // => 10
"10"   | 0 // => 10
"10.1" | 0 // => 10
"10.9" | 0 // => 10

你应该使用 JavaScript 的parseInt()

In ES6 , you can use builtin method trunc from Math Object

 Math.trunc(345.99933)

在此处输入图片说明

var num = 233.256;
console.log(num.toFixed(0));

//output 233

returns string:

(.17*parseInt(prescription.values)*parseInt(cost.value)).toFixed(0);

returns integer:

Math.round(.17*parseInt(prescription.values)*parseInt(cost.value));

Remember to use radix when parsing ints:

parseInt(cost.value, 10)

Mathematically, using a floor function makes the most sense. This gives you a real number to the largest previous integer.

ans7 = Math.floor(.17*parseInt(prescription.values)*parseInt(cost.value));

Have you try to get value using parseInt

Try :

console.log(parseInt(ans7));

~~ operator is a faster substitute for 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM