Jump to content

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);
Edited by Ch0cu3r
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 />";
?>
Edited by QuickOldCar
Link to comment
https://forums.phpfreaks.com/topic/285370-how-to-format/#findComment-1465271
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.