Truncate (not round) decimal places in sprintf?

Tag: perl , printf , mod-perl Author: liyuangyuang2007 Date: 2012-03-03

I want to display the dollar value with two digits after the decimal point to denote the cents. In the below program the output is 23.24. Perl rounds the decimal places. How to avoid it. I want the output to be 23.23.

$testa=sprintf("%.2f", $val);
print "\n$testa\n $val";
You want it to always truncate?
Calculate in pennies instead of dollars, and then use int to truncate fractional pennies.

Best Answer

print int(23.2395*100)/100;  # => 23.23


No need for the printf decorum
Thanks a lot for the info

Other Answer1

Math::Round has different rounding methods.

use Math::Round 'nlowmult';
print nlowmult( 0.01, 23.2395 ); # 23.23


Thanks a lot for the info