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

53 lines
1.2 KiB
Perl
Raw Normal View History

2012-02-29 15:21:49 -08:00
package DDG::Goodie::SigFigs;
# ABSTRACT: Count the significant figures in a number.
2012-02-29 15:21:49 -08:00
use strict;
2012-02-29 15:21:49 -08:00
use DDG::Goodie;
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 $_;
}
2015-12-27 11:15:11 -08:00
return $len, structured_answer => {
id => 'sig_figs',
name => 'Answer',
data => {
title => "$len",
subtitle => "Significant figures of $_",
},
templates => {
group => 'text',
moreAt => 0,
},
};
2012-02-29 15:21:49 -08:00
};
1;