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.

leente said...

Ada has it too

MickeyC said...

You didn't look very hard then:

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

Nathan 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 fusion hcm online Training 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