删除字符串右侧的特定字符
问题描述:
I need to remove zeros from the end of a string, but only up to 2 places from the right of a decimal point.
I'got a formatted price being handed over as a string, and that price is up to 5 decimal places. I need to strip unnecessary zeros from the price but leaving at least 2 to the right of a decimal place. For example:
£0.00230 -> £0.0023 and £1.50000 -> £1.50
Any help would be appreciated!
答
Final and last update hopefully... trim off all the zeros on the right then add 1 or 2 zeroes if needed.
function format_number($price) {
if (preg_match('~^£\d+$~', $price)) {
$price .= '.00';
} else {
$price = rtrim($price, '0');
if (preg_match('~\.$~', $price)) {
$price .= '00';
} elseif (preg_match('~\.\d$~', $price)) {
$price .= '0';
}
}
return $price;
}
echo format_number('£230') . "
";
echo format_number('£230.12') . "
";
echo format_number('£23.024') . "
";
echo format_number('£230.00024') . "
";
echo format_number('£230.0240') . "
";
echo format_number('£230.2') . "
";
Output:
£230.00
£230.12
£23.024
£230.00024
£230.024
£230.20
答
Try this code:
$value = "0.00230";
$new_value = explode(".", $value);
$substring = substr($new_value[1], 0, 1);
if($substring == "00"){
$value = number_format($value, 4, '.', '');
} else {
$value = number_format($value, 2, '.', '');
}
echo $value;
答
You can remove the symbol, cast to float to remove trailing zeros, and use number_format
to add them back if needed:
function fixCurrency($string, $symbol){
//remove £, and any trailing zeros
$val = (float) ltrim($string, $symbol);
//add back zeros if needed
$parts = explode('.', $val);
if(!isset($parts[1]) || strlen($parts[1]) < 2){
$val = number_format($val, 2);
}
return $symbol . $val;
}