leo
leo

Reputation: 8520

number_format without rounding

Is there a number_format alternative in PHP that allows me to chose thousands and decimal separator, while keeping the number of decimals? E.g. something like this:

number_format_alternative( '1234.617', ',', '.' );

>1 234,617

but

number_format_alternative( '120.0', ',', '.' );
>120.0

I realize that I could achieve almost the same thing, by using a ridiculously high number of decimals, and trimming all zeros from the right, though the second example would then look like:

number_format_alternative( 120.0, ',', '.' );
>120

 

edit: This is what I ended up doing:

function numberOfDecimals( $number ) {
   return strlen(strstr(rtrim(sprintf('%.10F', $number), '0'), '.'))-1;
}

Upvotes: 0

Views: 878

Answers (1)

Oracle
Oracle

Reputation: 318

Since you are inputting the number to the function as a string you could use a regular expression to see how many digits are after the decimal point, represented by '.' in this case, and then execute number_format with the $decimals parameter set to the number you just calculated.

One regular expression that would work would be \.\d+ and then minus 1 off the length to find the decimals number, you could use a look behind how ever I think the performance would be worse. Some testing may be needed and I am sure there will be other regular expressions that would work.

Upvotes: 1

Related Questions