I'm trying to figure out how to use sprintf to print at least two decimal places and no leading zeros. For instance
input:
23
23.0
23.5
23.55
23.555
23.0000
output:
23.00
23.00
23.50
23.55
23.555
23.00
any formatting help would be appreciated
There is no such built-in format specifier. You could check if the number to be printed has two or fewer decimals (round to two decimals and compare), and if so use %.02f. If the number has more decimals, use a %g specifier. Here's an example in Ruby:
def print_two_dec(number)
rounded = (number*100).to_i / 100.0
if number == rounded
printf "%.02f\n", number
else
printf "%g\n", number
end
end
[ 23, 23.0, 23.5, 23.55, 23.555 ].each do |number|
print_two_dec(number)
end
Outputs:
23.00
23.00
23.50
23.55
23.555
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With