in reply to Re: Re: Rounding to a Given Number of Significant Figures Rather Than Decimal Places
in thread Rounding to a Given Number of Significant Figures Rather Than Decimal Places

In that case, to a first approximation you could do something like the following:

#! /usr/bin/perl -w use strict; while( <DATA> ) { chomp; my $nr = squeeze($_); print "[$nr] $_\n"; } sub squeeze { my $n = sprintf( '%0.8f', $_[0] ); $n =~ s/^0//; substr( $n, 0, 8 ); } __DATA__ 12345678901234567890 1234567890 1234567.0 1234567.9 123456.789012345 12345 123.4567 123.4 .1 .1234567890 0.00000999999

Then again, the few test cases here reveal a certain number of bugs. I contend that the results to squeeze() contain a bug, in that 1234567.0 and 1234567.9 return the same results, but in truth the latter should return 1234568. I don't know whether you will hit these borderline cases or not.

Maybe there's yet another module that deals with your problem.

<update>In response to gjb's remark about whether this code is a good idea or not, I was trying to point out the folly of storing numbers in fixed-width fields. The idea being that when you see what this outputs, maybe you better start thinking about overflow conditions. As I don't know the domain. I can't really deal with in a satisfactory matter (at least to my standards). I prefer to let the code stand as it is.</update>


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

Replies are listed 'Best First'.
Re: Re:x3 Rounding to a Given Number of Significant Figures Rather Than Decimal Places
by gjb (Vicar) on Jan 13, 2003 at 15:59 UTC

    I don't really think that this piece of code is such a good idea: representing 12345678901234567890 as 12345678 doesn't make sense in any situation I can think of.

    I'd suggest the author to check what he's written and either to modify or motivate this program.

    Update: Fair enough given the update grinder added.

    Just my 2 cents, -gjb-