I'd imagine there's a module out there to do this, but I just threw this together in a couple of minutes. Besides, it was fun. :)
There are lots of times that I need to figure out this kind of stuff - I live on a boat and ride a motorcycle, so I'm always wrenching on something. In fact, I did something like this many, many years ago, but somehow managed to lose track of it... actually, I recall that implementation being quite a naive one (I was just starting to learn programming then.) Hope it's of use to others as well!
#!/usr/bin/perl # By: Ben Okopnik <ben@okopnik.com>, 07:45 2012-07-16 # Finds nearest "tape measure" fraction for a given decimal use warnings; use strict; die "Usage: ", $0 =~ /([^\/]+)$/, " <number> [tolerance]\n" unless @ARGV && $ARGV[0] =~ /^(\d+)?(\.\d+)$/; # Yep, positives o +nly :) my $int = $1 || 0; my $dec = $2; die "No mantissa\n" unless $dec > 0; die "Not a reasonable tolerance\n" if $ARGV[1] && $ARGV[1] !~ /^0?\.\d+$/; my $tolerance = $ARGV[1] || .001; # 1 mil is the default my $denom = 2; { for my $num (1 .. $denom - 1){ die $int + $dec, " is equal to $int $num/$denom (+/-$tolerance +)\n" if abs($dec - $num / $denom) <= $tolerance; } $denom *= 2; redo; }
-- I hate storms, but calms undermine my spirits. -- Bernard Moitessier, "The Long Way"
In reply to Decimals to fractions by oko1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |