Skip to content

Instantly share code, notes, and snippets.

@kyrylo
Created November 11, 2012 01:23
Show Gist options
  • Select an option

  • Save kyrylo/4053280 to your computer and use it in GitHub Desktop.

Select an option

Save kyrylo/4053280 to your computer and use it in GitHub Desktop.
Count digits in an integer number
# (1)
# Meh.
num = 6969
num.to_s.length #=> 4
# (2)
# Hm...
num = 6969
len = 0
begin
len += 1
end while (num /= 10) > 0
p len #=> 4
# (3)
# Ah!..
num = 6969
Math.log10(num).floor.succ #=> 4
# But...
num = -6969
Math.log10(num).floor.succ #=> Math::DomainError: Numerical argument is out of domain - "log10"
# Well.
Math.log10(num.abs).floor.succ #=> 4
# Oh!
num = 0
Math.log10(num).floor.succ #=> FloatDomainError: -Infinity
# Mhm.
Math.log10(num.zero? && 1 || num).floor.succ #=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment