getting the length of a number

snowjoke

New Member
Joined
Nov 15, 2010
Messages
47
... by which I mean the number of digits in a number.

Code:
Function getLength(a)
    Length = Int(Log(a) / Log(10)) + 1
    getLength = Length
End Function
Fails on some corner cases, e.g. getLength(1000) = 3 (incorrect), but getLength(1001) = 4.

I could convert to a Variant(String) and measure that, but is there a better way using numbers?

Just thought of
Code:
do while a > 0
   a = a / 10
   Length = Length + 1
loop
look good?
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
Code:
Function getLength(a)
    getLength = Len(Format(a, "0"))
End Function

Format "0" is just an integer format (you could change that if you want), so 1000 and 1000.1 and 1001 all return 4

If you wanted to have a cell formula...
=LEN(TEXT(A1,"0"))
...will give you the length of the integer in cell A1

You may want to use the ABS function to exclude the negative sign in the length for negative numbers.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,595
Messages
6,179,798
Members
452,943
Latest member
Newbie4296

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top