php - Converting to and from CENTS -
php - Converting to and from CENTS -
so know there have been multiple questions regarding money , converting , cents. heck have asked one, want create different question hope there no duplicates out there.
so have created function takes dollar value , sends cents. think have slight problem code , hoping can tweaked little.
$money4 = "10.0001"; // converted cents, can see it's off. $money41 = "1001"; // when "1001", get's set in database, , homecoming money variable. // get, "$10.01"... have leak in amounts... rounded sec point. so have done, have used functions made this.
// gets dollar figure, or cent's figure if requested. function stripmoney($value, $position = 0, $returnas = "") { // have decimal? if(isset($value) && strstr($value, ".")) { // strip out numbers, decimals , negative $value = preg_replace("/([^0-9\.\-])/i","",$value); $decimals = explode(".", $value); // homecoming dollars default homecoming ($returnas == "int" ? (int)$decimals[$position] : $decimals[$position]); } elseif(isset($value)) { // if no decimals, lets homecoming solid number $value = preg_replace("/([^0-9\.\-])/i","",$value); homecoming ($returnas == "int" ? (int)$value : $value); } } the next function utilize generate cents or homecoming dollars.
function convertcents($money, $cents = null, $tocents = true) { if(isset($money)) { if($tocents == true) { // convert dollars cents $totalcents = $money * 100; // if have cents, lets add together them on if(isset($cents)) { $centscount = strlen($cents); // in case inputs, $1.1 // add together 0 end of var create accurate if($centscount < 2) { $cents = "{$cents}0"; } // add together cents $totalcents = $totalcents + $cents; } // homecoming total cents homecoming $totalcents; } else { // convert cents dollars $totaldollars = $money / 100; homecoming $totaldollars; } } } and final function puts together. utilize 1 function merge 2 functions basically.
function convertmoney($value, $tocents = true) { if(isset($value) && strstr($value, ".")) { homecoming convertcents(stripmoney($value, 0), stripmoney($value, 1), $tocents); } elseif(!empty($value)) { homecoming convertcents(stripmoney($value, 0), null, $tocents); } } what have done might overkill, think it's solid, other 1 detail, can see.
can help me these adjustments?
do not utilize floating point arithmetic if need exact answers. applies languages, not php. read big warning in php manual.
instead check out bc math or gmp extension. latter works integer numbers interested in bc math.
php numbers money money-format
Comments
Post a Comment