Truncate (not round) decimal places in sprintf?
Asked Answered
C

2

5

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";
Conjure answered 20/3, 2012 at 5:29 Comment(2)
You want it to always truncate?Formula
Calculate in pennies instead of dollars, and then use int to truncate fractional pennies.Carrasquillo
H
12
print int(23.2395*100)/100;  # => 23.23
Haulm answered 20/3, 2012 at 5:50 Comment(1)
No need for the printf decorumFilberto
C
7

Math::Round has different rounding methods.

use Math::Round 'nlowmult';
print nlowmult( 0.01, 23.2395 ); # 23.23
Cincinnatus answered 20/3, 2012 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.