简体   繁体   English

在JavaScript中删除小数点后的数字

[英]Remove numbers after decimal in javascript

var randomNumber = (Math.random()*3 + 3.5); randomNumber;

alert(randomNumber)

This piece of code returns a number like 这段代码返回一个数字,例如

4.589729345235789 4.589729345235789

I need it to return 我需要它回来

4.5 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? 因此,需要删除小数点后的所有数字(第一个数字除外),有人可以告诉我该怎么做吗?

You use Number.prototype.toPrecision() with parameter 2 , Number.prototype.toFixed() with parameter 1 . 您可以将Number.prototype.toPrecision()与参数2 ,将Number.prototype.toFixed()与参数1

+randomNumber.toPrecision(2);

Alternatively, you can use String.prototype.slice() with parameters 0 , 3 可替换地,可以使用String.prototype.slice()与参数03

+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. 如果需要在数字中设置小数位数,则可以使用toFixed(X) ,其中X是您想要的小数位数。

For example, 例如,

4.589729345235789.toFixed(1); would result in 4.6 . 将导致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: 如果您需要绝对精度,而4.6还不足以满足您的需求,请参阅此Stackoverflow帖子 ,该帖子针对您的情况提供了一种更为“准确”的方法:

var with2Decimals = num.toString().match(/^-?\\d+(?:\\.\\d{0,2})?/)[0]

Notice the {0,2} inside of that, which is the range. 请注意其中的{0,2} ,即范围。 You can change it to {0,1} in your case. 您可以根据情况将其更改为{0,1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM