PHP separate string

前端 未结 2 1498
暖寄归人
暖寄归人 2021-01-29 16:39

I have a string that contains 128.82. I want to split/separate them in 100 and 28.82.

var_dump(substr($kwh,0,3));
        d         


        
相关标签:
2条回答
  • 2021-01-29 16:55
    $input = '128.82'; // we’re doing math here, so actually we’ll be working with numbers,
                       // but PHP will automatically cast here
    $slabs = [50, 100, 150, 200];
    
    $result = [];
    $previous_slab = 0;
    
    foreach($slabs as $slab) {
      // calculate distance between current and previous slab
      $slab_distance = $slab - $previous_slab;
      // if current remainder of input value is >= distance, add distance to result,
      // and subtract distance from remainder of input
      if( $input >= $slab_distance ) {
        $result[] = $slab_distance;
        $input -= $slab_distance;
      }
      // otherwise, add remainder as last item of result, and break out of the loop here
      else {
        $result[] = $input;
        break;
      }
      $previous_slab = $slab;
    }
    
    var_dump($result);
    

    Result for the given slabs:

    array (size=3)
      0 => int 50
      1 => int 50
      2 => float 28.82
    

    Result for [50, 75, 150, 200]:

    array (size=3)
      0 => int 50
      1 => int 25
      2 => float 53.82
    
    0 讨论(0)
  • 2021-01-29 17:04

    If you want to split 128.82 into 100 and 28.82 You can do it like this:

    <?php
    function calcSlabSize($size) {
        $slab = floor($size / 50)*50;
        return [$slab,$size-$slab];
    }
    
    print_r( calcSlabSize(128.82));
    

    This will result in:

    Array ( [0] => 100 [1] => 28.82 ) 
    
    0 讨论(0)
提交回复
热议问题