Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify decimal point and thousands separator without changing the number of decimals

I'm new to php and I'm trying to use number_format :

number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

As in the title, my goal is to modify decimal point and thousands separator without changing the number of decimals as below:

$Num=123456.789;
$Num2=number_format ($Num, [decimals as in $Num], ",", "'" );

My result should be:

$Num2="123'456,789";

Edit

I need a code for an unknown number of decimals

like image 561
genespos Avatar asked Oct 17 '25 15:10

genespos


1 Answers

You can use NumberFormatter.

You will still need to specify a certain amount of fraction digits, but you can just use a high enough value and be fine. It's not like the number of digits is really arbitrary. It's tied to your precision ini setting.

$formatter = new NumberFormatter("en_US", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 42);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "'");
$formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, ",");
echo $formatter->format(123456.7891234); // 123'456,7891234

Demo https://3v4l.org/TCAIA

like image 177
Gordon Avatar answered Oct 20 '25 05:10

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!