in reply to Stupid sprintf question - decimals

Hi Andy,
What does
perl -e '$num=12314212412124124124.10623;print "initial:\t$num\n";prin +tf ("formatted:\t%f\n",$num);printf ("rounded:\t%.2f\n",$num);' initial: 1.23142124121241e+19 formatted: 12314212412124123136.000000 rounded: 12314212412124123136.00
tell you?

that's a very bignum and printf won't handle it

#!/usr/bin/perl use strict; use warnings; use bignum; sub rounder{ my ($prec,$num)=@_; my $round=0.5 / (10**$prec); $num+=$round; $num=~ s/(\.\d{$prec})\d*$/$1/; return $num; } my$num=12314212412124124124.10623; print "initial:\t$num\n"; print "rounded:\t", rounder(2 ,$num),"\n"; __END__ initial: 12314212412124124124.10623 rounded: 12314212412124124124.11
print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."

Replies are listed 'Best First'.
Re^2: Stupid sprintf question - decimals
by Anonymous Monk on Oct 12, 2010 at 15:38 UTC
    ...as an alternative, use precision():

    $ perl -Mbignum -le 'my $x = 12314212412124124124.10623; $x->precision +(-2); print $x;' 12314212412124124124.11
Re^2: Stupid sprintf question - decimals
by ultranerds (Hermit) on Oct 12, 2010 at 15:51 UTC
    ah thanks guys - didn't realise there was a limit with the size of number you could use ;) (that was only a simple test number)

    I've shorted it, and works fine now <G>

    Thanks again

    Andy