如何使用 JavaScript 删除小数点后的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12423755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:56:41  来源:igfitidea点击:

How to remove digits after decimal using JavaScript?

javascript

提问by Shahzad CR7

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

我在 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>

回答by vzwick

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

假设您只想截断小数部分(不四舍五入),这里有一个更短(更便宜)的parseInt()or替代方案Math.floor()

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


Further examples for the bitwise OR 0behavior with int, floatand stringinput:

bitwise OR 0使用int,floatstring输入的行为的更多示例:

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

回答by John Conde

You should use JavaScript's parseInt()

你应该使用 JavaScript 的 parseInt()

回答by allsyed

In ES6 , you can use builtin method truncfrom Math Object

在 ES6 中,您可以使用truncMath Object 的内置方法

 Math.trunc(345.99933)

enter image description here

enter image description here

回答by g1ji

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

//output 233

回答by Jakub Konecki

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)

回答by Aesthete

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

在数学上,使用floor函数最有意义。这给你一个实数到最大的前一个整数。

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

回答by Jignesh Rajput

Have you try to get value using parseInt

你有没有尝试使用 parseInt

Try :

尝试 :

console.log(parseInt(ans7));

回答by Penny Liu

Try to use ~~mynumberfor eliminate decimals.

尝试~~mynumber用于消除小数。

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>