admin管理员组文章数量:1318958
var randomNumber = (Math.random()*3 + 3.5); randomNumber;
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
var randomNumber = (Math.random()*3 + 3.5); randomNumber;
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
Share Improve this question asked Dec 31, 2016 at 4:39 MattMatt 1731 silver badge14 bronze badges2 Answers
Reset to default 5You use Number.prototype.toPrecision()
with parameter 2
, Number.prototype.toFixed()
with parameter 1
.
+randomNumber.toPrecision(2);
Alternatively, you can use String.prototype.slice()
with parameters 0
, 3
+String(randomNumber).slice(0, 3);
If you need to set the amount of decimal places in a number, you can use toFixed(X)
, where X is the amount of decimal places you want to have.
For example,
4.589729345235789.toFixed(1);
would result in 4.6
.
Keep in mind, this will convert the number into a string.
If you need absolute accuracy and 4.6
is not good enough for you, see this Stackoverflow post, which has this as a more "accurate" method for your case:
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
Notice the {0,2}
inside of that, which is the range. You can change it to {0,1}
in your case.
本文标签: Remove numbers after decimal in javascriptStack Overflow
版权声明:本文标题:Remove numbers after decimal in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742058571a2418445.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论