在 JavaScript 中从数字中删除小数点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18248752/
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-10-27 11:12:19  来源:igfitidea点击:

Remove decimal point from number in JavaScript

javascript

提问by JVE999

I would like to remove the decimal, but keep all of the digits.

我想删除小数,但保留所有数字。

All I can think of is to find the length of the number and find out which power of 10 it's just larger than, then multiply. Although, I can't find how to find the length of a number.

我能想到的就是找出数字的长度并找出它比 10 的哪个幂大,然后相乘。虽然,我找不到如何找到数字的长度。

采纳答案by Anand

i should not do it but look at this fiddle

我不应该这样做,但看看这个小提琴

var d = 109.65;
var s = d + '';
s =s.replace('.', '');
s = parseInt(s);
alert(s);

回答by Jimmy

var newnumber = parseInt(num.toString().replace(".", ""), 10);

回答by Rory McCrossan

Use replace:

使用replace

var num = 1234.5678;
alert((num + '').replace('.', ''));

回答by Daniil Grankin

Try this

试试这个

parseInt(num.toString().replace('.', ''))

回答by Matthew Riches

If you want a more generic way which will remove all non numerics you could use:

如果您想要一种更通用的方法来删除所有非数字,您可以使用:

var num = 1234.5678;
var str = new String(num); 
alert(str.replace(/[^0-9|-]/g, ""));

and if it needs to be a number afterwards just wrap it in a parseInt.

如果之后它需要是一个数字,只需将它包装在 parseInt 中。