问题
how to convert all numbers to xx,xx decimal format without exploding number or string? like;
8,9 --> 8,90
8,99 --> 8,99
12,1 --> 12,10
129,9 --> 129,90
any idea?
回答1:
You can use number_format like:
$n = 2.1;
echo number_format($n, 2, ','); // 2,10
If you have commas as decimal separators in your input you can convert values to float with:
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
str_replace('.', '', $string_number)
is used to remove thousand separators.
str_replace(',', '.', ... )
is used to replace commas with dots.
回答2:
If you have the intl
extension enabled, the best approach to the issue (IMO) is given in the accepted answer to this question: PHP: unformat money
You can use
- NumberFormatter::parseCurrency - Parse a currency number
Example from Manual:
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY); var_dump($formatter->parseCurrency("75,25 €", $curr));
gives:
float(75.25)
Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.
After that, you'll have a float value and formatting that is a trivial issue using number_format()
.
If you do not have that extension, check out the regex approach in this question: What a quick way to clean up a monetary string
回答3:
$money = number_format($number, 2, ",", ","); // $number must be a float, i.e 8.8
If your inputs have to have commas as decimal separators, do this too:
$money = "20,2";
$fixed_money = floatval(str_replace(",", ".", $money));
echo number_format($fixed_money, 2, ",", ",");
回答4:
str_pad will add the missing zero
$val = '1008,95';
$len = strpos($val, ',') + 3;
$newval = str_pad($val, $len, '0', STR_PAD_RIGHT);
echo "Value: " . $newval . "<br>";
You have to be sure that your values don't have more than two decimal digits, though
回答5:
I made a composer package that can deal with such things depending on which currency you are displaying.
https://packagist.org/packages/votemike/money
If you also enter the country it will format the currency in the local way (with or without commas and with the correct number of decimal places)
$money = new Money(99.50, 'JPY');
$money->format(); //¥100
And so if you just create a new money object with the amount you want to display and the currency you are displaying it in, calling ->format() on that object should give you the result you're looking for.
来源:https://stackoverflow.com/questions/14232718/decimal-money-format