views:

188

answers:

1

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

A: 

There is no such built-in format specifier. You could check if the number to be printed as 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
calmh