darp Posted October 27, 2008 Share Posted October 27, 2008 While filling out a form I want the data to be stored in both metric and standard. The figures for the standard entries need only be accurate to the nearest quarter ounce. So the user input is grams and that figure is automatically divided by 28.349523125 to get the equivalent ounces. The problem is, entries like 100 grams are converted to 3.52739619496 ounces. What I would really like to see is 3.5 ounces and 92 grams converted to 3.25 ounces instead of 3.24520449936. The only values that I want to see are *.00 || *.25 || *.50 || *.75 Is this possible? P.S. The reason the original entry has to be in grams is because most of the original data is provided that way so doing the conversion the other way is not really an option. Quote Link to comment Share on other sites More sharing options...
jonsjava Posted October 27, 2008 Share Posted October 27, 2008 You'll want to use round() it's used as such: <?php $data = "3.52739619496"; print round($data, 2); Number first, then the decimal place you want to round to Quote Link to comment Share on other sites More sharing options...
Jeremysr Posted October 27, 2008 Share Posted October 27, 2008 The only way I can think of is doing it manually like this: function round_to_quarter($num) { $floor = floor($num); $fractional_part = $num - $floor; if ($fractional_part < 0.125) { return $floor; } if ($fractional_part < 0.375) { return $floor + 0.25; } if ($fractional_part < 0.625) { return $floor + 0.5; } if ($fractional_part < 0.875) { return $floor + 0.75; } return $floor + 1; } It's not very pretty, but I can't think of another way. Quote Link to comment Share on other sites More sharing options...
genericnumber1 Posted October 27, 2008 Share Posted October 27, 2008 <?php function roundQuarter($num) { return round($num * 4) / 4; } echo roundQuarter(25.99); // 26 echo roundQuarter(24.3); // 24.25 // etc... ?> To explain... to round to decimal x, multiple the number by (1/x) - in this case, 1/.25 results in 4, round normally, and then divide it by 1/x again. A more general formula would be: <?php function roundDecimal($num, $decimal) { $tmp = 1 / $decimal; return round($num * ($tmp)) / $tmp; } echo roundDecimal(25.34, 0.1); // rounds to the nearest tenth ?> Quote Link to comment Share on other sites More sharing options...
darp Posted October 27, 2008 Author Share Posted October 27, 2008 Thanx genericnumber1. That works great. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.