Wednesday, September 8, 2010

Code Readability: Quick, Millions or Billions?


It is really easy to get the order of magnitude wrong on a number in code. I had settled into the habit of carefully counting my digits to make sure it was right until one of my co-workers pointed out a neat feature of ruby.

Ruby allows underscores to be inserted into numbers between any two digits. The underscores are purely cosmetic and do not affect the value of the number. This feature allows a developer to use underscores as an accountant might use commas.

3193490646      # standard representation of a number in ruby
3_193_490_646   # same value, much more readable

One less excuse for order of magnitude errors when using ruby.

A little looking around did not find any similar functionality in other languages, I checked into C/C++, Smalltalk, Python, Perl, PHP, Java, Javascript, Lisp, and Erlang. I am very curious to know if anyone knows of another language or particular implementation of one of the listed languages that supports similar functionality.

Thanks to Dallas Reedy for introducing me to this awesome feature of Ruby


Shane said...

Perl does indeed have this feature.

Anonymous said...

Ada has it too

Unknown said...

You didn't look very hard then:

mike@snail:~$ perl -e 'print "".(1_000_000)."\n"'

Unknown said...

Cool, after it was mentioned that Perl does this I poked around a little more and found that only about half of the sites that explain Perl's numeric formats point this feature out.

Some of my friends that do Smalltalk pointed out that it would be very easy to add this to Smalltalk.

Sam Livingston-Gray said...

"Some of my friends that do Smalltalk pointed out that it would be very easy to add this to Smalltalk."

...but then, they probably say that about everything. (=

oracle procurement said...

Commenting on a blog is a painting. correct comments create members of the circle of relatives. you’re doing amazing work. very high-quality I surely like your weblog......
thanks for sharing
oracle fusion procurement online training
oracle fusion procurement training


this is very informative post.keep posting such a post.
oracle fusion SCM online training

Unknown said...

Great post, Thanks a lot for the kind of perfect topic I have not a lot of information about it but I have got an extra unique info in your unique post.
eCommerce Product Upload Service

hotmail said... , free live cams & free live chat with Live cam girls , adult chat cams, be a live cam girl,