zeroclickinfo-goodies/lib/DDG/Goodie/SigFigs.pm

50 lines
1.3 KiB
Perl
Raw Normal View History

2012-02-29 15:21:49 -08:00
package DDG::Goodie::SigFigs;
use DDG::Goodie;
2012-11-06 13:56:31 -08:00
primary_example_queries 'sigfigs 01.1234000';
2012-11-06 14:48:08 -08:00
secondary_example_queries 'significant figures 000123000';
2012-11-06 13:56:31 -08:00
description 'return the count of significant figures in a number';
name 'Significant Figures';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/SigFigs.pm';
category 'calculations';
topics 'math';
attribution github => ['https://github.com/hunterlang', 'hunterlang'];
2012-03-05 13:04:59 -08:00
triggers start => 'sigfigs', 'sigdigs', 'sf', 'sd', 'significant';
2012-03-20 21:08:12 -07:00
zci answer_type => "sig_figs";
2012-03-24 11:05:13 -07:00
zci is_cached => 1;
2012-02-29 15:21:49 -08:00
handle remainder => sub {
$_ =~ s/^(figures|digits)\s*//g;
2012-03-08 10:48:56 -08:00
return unless /^-?\d+(?:\.(?:\d+)?)?$/;
2012-02-29 15:21:49 -08:00
$_ =~ s/-//;
$_ =~ s/^0+//;
my @arr = split('\\.', $_);
my $v = @arr;
my $len = 0;
# there's a decimal
unless ($v eq 1) {
# the string doesn't have integers on the left
# this means we can strip the leading zeros on the right
if ($_ < 1) {
$arr[1] =~ s/^0+//;
$len = length $arr[1];
}
#there are integers on the left
else {
$len = length($arr[0]) + length($arr[1]);
}
}
# no decimal
else {
# lose the trailing zeros and count
$_ =~ s/\.?0*$//;
$len = length $_;
}
return "Significant figures: $len";
};
1;