Roman Toasov
Roman Toasov

Reputation: 821

PHP format decimal part of number

I have number 0.000432532 i want to break decimal part thousands like this

0.000 432 532 

number_format() is only formats the whole part of the float, not decimal part.

Is there single function that can do it?

Upvotes: 1

Views: 411

Answers (3)

Don't Panic
Don't Panic

Reputation: 41820

A regex method will be more efficient than all this various array conversion, but just for the sake of argument, it can be done without regex:

list($int, $dec) = explode('.', $number);
$result = implode('.', [$int, implode(' ', str_split($dec, 3))]);

for a regex, I think this should handle most cases:

$formatted = preg_replace('/(\d+\.\d{3}|\d{3})(?!$)/', '$1 ', $number);

Upvotes: 1

Spoody
Spoody

Reputation: 2882

Andreas answer will work fine as long as you use numbers that are smaller than 99, however if you are planning to use >99 numbers, I suggest this:

$input = '0.000432532';

// Explode number
$input = explode('.', $input);

// Match three digits
$regex = '/(\d{3})/';
$subst = '$1 '; // substitute with the digits + a space
// Use number format for the first part
$input[0] = number_format($input[0], 0, '', ' ');
// User regex for the second part
$input[1] = preg_replace($regex, $subst, $input[1]);

echo implode($input, '.');

this one will work for all numbers

Upvotes: 1

Andreas
Andreas

Reputation: 23968

Don't know if there is a better solution but regex will do it.

$re = '/(\d{3})/'; // match three digits
$str = '0.000432532';
$subst = '$1 '; // substitute with the digits + a space

$result = preg_replace($re, $subst, $str);

echo $result;

https://regex101.com/r/xNcfq9/1

This has a limitation, the number can not be larger 99 or the integer part of the number will start to "break" up.
But it seems as you only use small numbers.

Upvotes: 2

Related Questions