Arav
Arav

Reputation: 5247

Truncate (not round) decimal places in sprintf?

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.

$val=23.2395;
$testa=sprintf("%.2f", $val);
print "\n$testa\n $val";

Upvotes: 5

Views: 9142

Answers (2)

dbenhur
dbenhur

Reputation: 20398

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

Upvotes: 12

stevenl
stevenl

Reputation: 6798

Math::Round has different rounding methods.

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

Upvotes: 7

Related Questions