如何使用javascript获取数字中的位数 [英] how to get number of digits in a number with javascript

查看:180
本文介绍了如何使用javascript获取数字中的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript计数数字位数.
例如
1-1位
11-2位
100-3位
1000-4 digit

i want count number of digit in number using javascript.
eg
1-1 digit
11-2 digit
100-3 digit
1000-4 digit

推荐答案

var numberOfDigits = Math.floor(Math.log(number) / Math.LN10 + 1)



尽管number等于零,但只返回1,就必须抓住极端情况.对于负数,您只需要使用绝对(Math.abs(x))值即可.

问候,

-曼弗雷德(Manfred)



You''ll have to catch the edge case though where number is equal to zero and just return 1. For negative numbers you just use the absolute (Math.abs(x)) value.

Regards,

—Manfred


尝试一下:
Try this:
<SCRIPT LANGUAGE="JavaScript">

function CountLeft(field, count, max)
 {
   if (field.value.length > max)
      field.value = field.value.substring(0, max);
   else
      count.value = max - field.value.length;
}
</script>


Math.ceil(Math.log(filterVal + 1)/Math.LN10)
Math.ceil(Math.log(filterVal + 1) / Math.LN10)


这篇关于如何使用javascript获取数字中的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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