Main Content

Divide 10000 by 17. Do you get 588.235294117647, 588.24 or 588? - Ruby and PHP

Archive - Originally posted on "The Horse's Mouth" - 2011-09-08 07:19:31 - Graham Ellis

If you divide £10,000 between 17 lucky children, each gets £588.23 ... but if you divide the number 10,000 by the number 17, you get 588.235294117647. How do you format the data to the appropriate number of decimal places?

In Ruby, you can use the % operator on a string - which is an alias for the sprintf function. Here's an example, showing each of the two ways embedded in a puts statement:

  puts "With #{'%-2d' % infavour} kids, each gets #{'%8.2f' % amount}"
  puts "With #{sprintf '%-2d',infavour} kids, each gets #{sprintf '%8.2f',amount}"


Full exaample - including a list of the more common formatting letters (the "d" and "f" in my example) - [here].

Ruby has plenty of variety, There's a further example of an almost identical application written on an earlier course - [here]. And in that I used the same % operator in a rather different way:

  print "With %-2d in favour (add %10.10s) each gets %06.2f\n" %
     [nif, names[currentname],howm]





Co-incidentally, my email last night included a similar question about PHP. My answer:

Sample PHP code that prints out number to full places, then just to 2:

  <?php
  $var = 296.531136;
  print ("$var\n");
  printf ("%.2f\n",$var);
  ?>


Runs as follows:

  wizard:sep11 graham$ php phpdemo
  296.531136
  296.53
  wizard:sep11 graham$


You'll find PHP examples in various places in our examples directory including [here] and [here].

In Perl and C, you have printf ... and in Python you have the % operator although there's also something new as well ... via str.format. See [here].