[英]How do i convert decimal value to single digit
Here is my question 这是我的问题
I want to convert 0.21 to 0.29 to 2 我想将0.21转换为0.29到2
then 0.31 to 0.39 to 3 till 0.99 to 9 然后0.31到0.39到3直到0.99到9
and so one 所以一个
I went to this function but it didn't help 我去了这个功能,但没有帮助
function myFunction() {
var num = 0.89;
var n = num.toFixed(1);
document.getElementById("demo").innerHTML = n +1;
}
Try using the following: 尝试使用以下内容:
function myFunction(num) {
document.getElementById("demo").innerHTML = Math.floor(num*10);
}
Easiest way to achieve what you want is: 实现所需目标的最简单方法是:
var num = 0.89; var n = Math.floor(num * 10) % 10; document.getElementById("demo").innerHTML = n;
<div id="demo"></div>
Without using any math functions. 不使用任何数学函数。 Because you want X of 0.XYZ every time. 因为您每次都希望X为0.XYZ。
You could use factor for flooring. 您可以使用因子作为地板。
function format(v) { var d = Math.floor(Math.log10(v)); return Math.floor(v / Math.pow(10, d)); } console.log([0.2, 0.89, 0.023, 5432].map(format));
var integer_value = Math.floor(num*10); // gives required integer value
Explanation: 说明:
If your number is 0.ABC, you want A, you can do this by multiplying 0.ABC by 10, which makes it A.BC and then using Math.floor on A.BC to get A. 如果您的数字是0.ABC,则需要A,可以通过将0.ABC乘以10来实现,即为A.BC,然后在A.BC上使用Math.floor来获得A。
Cases: 情况:
When 0.ABC: 当0.ABC:
toFixed(0) 固定(0)
toFixed(sig_digits) will give you a string representation of the number till a certain number of significant digits. toFixed(sig_digits)将为您提供数字的字符串表示形式,直到一定数量的有效数字为止。 Using that with sig_digits 0, will round it off, so cases like 8.99 will get rounded off to 9, instead of 8. 将其与sig_digits 0结合使用会四舍五入,因此像8.99这样的情况会四舍五入为9,而不是8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.