在JavaScript中删除小数点后的数字 [英] Remove numbers after decimal in javascript

查看:68
本文介绍了在JavaScript中删除小数点后的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

alert(randomNumber)

这段代码返回一个类似

4.589729345235789

我需要它返回

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?

推荐答案

如果您需要设置数字中的小数位数,则可以使用 toFixed(X),其中X是您想要的小数位数.

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.

例如,

4.589729345235789.toFixed(1); 将导致 4.6 .

请记住,这会将数字转换为字符串.

Keep in mind, this will convert the number into a string.

如果您需要绝对精度,而 4.6 对您来说不够好,请参阅

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]

请注意其中的 {0,2} ,即范围.您可以根据情况将其更改为 {0,1} .

Notice the {0,2} inside of that, which is the range. You can change it to {0,1} in your case.

这篇关于在JavaScript中删除小数点后的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆