Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf, sprintf print at least two decimal places

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

like image 918
PhilBrown Avatar asked Jun 03 '10 14:06

PhilBrown


1 Answers

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
like image 102
Jakob Borg Avatar answered Nov 09 '22 19:11

Jakob Borg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!