PHP separate string

若如初见. 提交于 2020-08-20 15:50:37

问题


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));
        die();

It gives me 128.

How can I separate the 100 and 28.82?

Any help would be highly appreciated

Note: I am setting this because I have defined slabs. 1-100, 101-150, and so on. So I need to set them according to the slabs. The slabs may differ as it could be 1-50, 51-100, 100-150, and so on. so I have to divide/split 128.82 like 50 for 1-50, 50 for 51-100 and then 28.82 for 101-150


回答1:


$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



回答2:


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 ) 


来源:https://stackoverflow.com/questions/63069762/php-separate-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!