Jump to content

how to format


DrTrans

Recommended Posts

Trim, explode and floor

$string = '(215.354100, 218.613800, 2501.263000)';

// trim the () from the start/end of string and explode on comma and space
$data = explode(', ', trim($string, '()'));
// apply floor to round number down to nearest whole integer (removes the decimal)
$data = array_map('floor', $data);

// create the new string
$new_string = sprintf('(%s)', implode(', ', $data));

echo "$string<br />$new_string";

Or a simple preg_replace with regex

$new_string = preg_replace('~(\.\d+)~', '', $string);
Link to comment
https://forums.phpfreaks.com/topic/285370-how-to-format/#findComment-1465263
Share on other sites

floor() easier, just another way

 <?php
$my_string = "(215.354100, 218.613800, 2501.263000)";
$my_array  = array(
    "215.354100",
    "218.613800",
    "2501.263000"
);

function format_numbers($input = '')
{
    if ($input == '') {
        return $input;
    }
    
    if (!is_array($input)) {
        $input = explode(",", $input);
    }
    
    $first_numbers = array();
    foreach ($input as $numbers) {
        $numbers         = trim($numbers);
        $numbers         = str_replace(array(
            "(",
            ")"
        ), '', $numbers);
        $end_numbers     = end(explode(".", $numbers));
        $first_numbers[] = str_replace(".$end_numbers", '', $numbers);
    }
    
    $formatted = "(" . implode($first_numbers, ",") . ")";
    return $formatted;
}

echo format_numbers($my_string) . "<br />";
echo format_numbers($my_array) . "<br />";
echo format_numbers() . "<br />";
?>
Link to comment
https://forums.phpfreaks.com/topic/285370-how-to-format/#findComment-1465271
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.