Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove digits after decimal using JavaScript?

Tags:

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>
like image 285
Shahzad CR7 Avatar asked Nov 27 '22 22:11

Shahzad CR7


2 Answers

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
like image 175
vzwick Avatar answered Dec 10 '22 01:12

vzwick


You should use JavaScript's parseInt()

like image 27
John Conde Avatar answered Dec 10 '22 02:12

John Conde