Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove numbers after decimal in javascript

Tags:

javascript

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?

like image 247
Matt Avatar asked Mar 12 '26 05:03

Matt


1 Answers

You 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);
like image 103
guest271314 Avatar answered Mar 14 '26 19:03

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!