Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Remove trailing zeroes without exponential value

Tags:

perl

I am trying to remove trailing zeroes from decimal numbers.

For eg: If the input number is 0.0002340000, I would like the output to be 0.000234

I am using sprintf("%g",$number), but that works for the most part, except sometimes it converts the number into an exponential value with E-. How can I have it only display as a full decimal number?

like image 240
user333746 Avatar asked Dec 29 '11 23:12

user333746


2 Answers

Numbers don't have trailing zeroes. Trailing zeroes can only occur once you represent the number in decimal, a string. So the first step is to convert the number to a string if it's not already.

my $s = sprintf("%.10f", $n);

(The solution is suppose to work with the OP's inputs, and his inputs appear to have 10 decimal places. If you want more digits to appear, use the number of decimal places you want to appear instead of 10. I thought this was obvious. If you want to be ridiculous like @asjo, use 324 decimal places for the doubles if you want to make sure not to lose any precision you didn't already lose.)

Then you can delete the trailing zeroes.

$s =~ s/0+\z// if $s =~ /\./;
$s =~ s/\.\z//;

or

$s =~ s/\..*?\K0+\z//;
$s =~ s/\.\z//;

or

$s =~ s/\.(?:|.*[^0]\K)0*\z//;
like image 162
ikegami Avatar answered Nov 15 '22 03:11

ikegami


To avoid scientific notation for numbers use the format conversion %f instead of %g.

like image 23
Ted Hopp Avatar answered Nov 15 '22 05:11

Ted Hopp