Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Commercial round currency

Dear Stackoverflowers,

I would like to know what sollutions you can come up with for the following problem:

This is what I have:

13.90
5.03
7.06
2.51

This is what I want:

13.90
5.05
7.05
2.50

Basically: I want to round currency on a commercial base. There last decimal may only be rounded up to 5 or 10 (adding one to the first digit) or rounded down to 5 or 0.

like image 257
halfpastfour.am Avatar asked Dec 10 '22 01:12

halfpastfour.am


2 Answers

A general formula for rounding to the nearest x:

round(input / x) * x

And an example for your use case:

round(5.03 / .05) * .05 = round(100.6) * .05 = 101 * .05 = 5.05
like image 114
Dylan Avatar answered Dec 22 '22 15:12

Dylan


<?php

$int = 5.03;
$int *= 20;
$int = ceil($int);
$int /= 20;

echo $int;

You just need to define the resolution of the rounding by multiplying the number (and later on dividing it again). It's a simple math problem.

like image 39
Madara's Ghost Avatar answered Dec 22 '22 15:12

Madara's Ghost