How to round currency values

I already have several ways to solve this problem, but I'm wondering if there is a better solution to this problem. Please answer only with a purely digital algorithm. String processing is not acceptable. I am looking for an elegant and effective solution.

Given the value of the currency (i.e. $ 251.03), divide the value into two halves and rounded to two decimal places. The key is that the first half should round, and the second should round. Thus, the result in this scenario should be $ 125.52 and $ 125.51.

+4
source share
4 answers

Divide by two, round to 2 dp (in C # it is decimal.Round(value, 2) ), subtract the rounded value from the original and sort them using if. Your library can maintain rounding control, which can save you if using C # you can do this using the 3-parameter decimal.Round overload.

+5
source
 money = amount_you_are_dividing bigmoney = ceiling((money / 2) * 100)/100 littlemoney = money - bigmoney 

This, of course, assumes that you have access to the math library with a ceiling function.

+1
source

I assume that you represent your currency using integers (rather than floating point), so the currency value Β€123.45 is represented by the integer v = 12345.

Then the greater part is (v + 1) / 2 , and the smaller part is v / 2 .

(If you use floating point numbers to represent a currency, see this question .)

0
source

Some php logic for rounding currency values ​​to a specified amount. (Penny, nickel, penny, quarter, 50c, dollar.)

The calling statement passes the original value as the first argument, and rounding (.05, .10, .25, .50, 1.00) as the second.

eg.

 $price = invtround{$value, .10} ; 

The function returns a rounded value.

 function invtround($x,$y) { if ($x == 0.01) { $result = $y ; } if ($x == .05) { $floor = round($y,1) ; if ($floor > $y) {$floor = $floor - $x ;} $diff = $y - $floor ; if ($diff < .03) {$result = $floor ;} else if ($diff < .08) {$result = $floor + .05;} else {$result = $floor + .10;} } if ($x == .10) { $floor = round(floor($y*10)/10,1) ; if ($floor > $y) {$floor = $floor - $x ;} $diff = $y - $floor ; if ($diff < .05) {$result = $floor ;} else {$result = $floor + .10;} } if ($x == .25) { $floor = floor($y*10)/10 ; $diff = $y - $floor ; if ($diff < .13) {$result = $floor ;} else if ($diff < .38) {$result = $floor +.25;} else if ($diff < .68) {$result = $floor + .50;} else if ($diff < .88) {$result = $floor + .75;} else {$result = $floor + 1.0;} } if ($x == .50) { $floor = floor($y*10)/10 ; $diff = $y - $floor ; if ($diff < .25) {$result = $floor ;} else if ($diff < .75) {$result = $floor + .50;} else {$result = $floor + 1.0;} } if ($x == 1.00){$result = round($y,0) ;} $result = number_format($result,2); return $result ; } 
0
source

All Articles