如何使用 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
How to remove digits after decimal using 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 0
behavior with int
, float
and string
input:
bitwise OR 0
使用int
,float
和string
输入的行为的更多示例:
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
回答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 floor
function 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 ~~mynumber
for 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>