1

I need to ensure the product price either gets 0 appended to it with decimal point removed if there is only one digit after the decimal point or 00 appended if there is no decimal point. The logic I could come up with so far is as follows. I would request SO to enlighten me on making this work with your correction. Thanks

Suppose the product price is 458.99 I need it to be 45899- only remove the period. Suppose the product price is 458.9 I need it to be 45890 Suppose the product price is 458 I need it to be 45800

$str=$_product->getFinalPrice(); 
if (!is_int($str) {
    if (strpos($str, '.') === false )) {
        $new_str = $val . 00;   
    } elseif (strlen(substr(strrchr($str, "."), 1)) == 1{
        $new_str = str_replace('.','', $str) . 0; 
    } elseif (strlen(substr(strrchr($str, "."), 1)) == 2 {
        $new_str = str_replace('.','', $str);
 }
1

Please try the below code. I have checked and it worked as per your requirement.

$price = 458.99; 
// $price = 458.9; 
// $price = 458; 

if (!is_int($price)) {
    if (strpos($price, '.') === false ) {
    $newPrice = $price . '00';   
    } 
    else if (strlen(substr(strrchr($price, "."), 1)) == 1 ){
        $newPrice = str_replace('.','', $price) . 0; 
    } 
    else if (strlen(substr(strrchr($price, "."), 1)) == 2 ){
        $newPrice = str_replace('.','', $price);
    }
} else {    
    $newPrice = $price . '00';
}

echo $newPrice; // return 45899

Please accept as an answer if work for you.

| improve this answer | |
  • thanks. I arrived at the same logic a little while ago except for the the last else block which is too important. – CodeForGood May 16 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.