Round up to decimal precision (Javascript and PHP)

I needed to round up to two decimal places for currency (you always round up when using money), but for some reason the internet didn’t want to share that information with me, so here it is.

PHP:

//  Takes a decimal and rounds up (never down)
function round_up($val, $precision) {
  return round($val + pow(10,-$precision-1), $precision);
}

Javascript:

function round_up (val, precision) {
    power = Math.pow (10, precision);
    poweredVal = Math.ceil (val * power);
    result = poweredVal / power;

    return result;
}

So, using round_up (1.432, 1); would return 1.5. For currency you’d want to set the precision (the number of decimal places you want) to two.

This entry was posted in Programming. Bookmark the permalink.

2 Responses to Round up to decimal precision (Javascript and PHP)

  1. John says:

    Why would you want to always round up when dealing with money? Doing so maximizes your rounding error! Better: round up on even numbers, round down (truncate) on odd numbers (or visaversa)

  2. Shane says:

    Rounding errors don’t so much matter when you want to make the most money you can. You always want that extra penny!

    You just have to decide which times you want to lower the figure (VAT for instance), and which to increase it (your sell price).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>