さまざまな長い数値があり、それらを正しくフォーマットする関数を作成しようとしています。誰かが私を助けることができますか?
すでに「number_format()
」と「round()
」を試しましたが、問題は解決しません。
次のように丸めたいと思います。
1024.43 --> 1,024.43
0.000000931540 --> 0.000000932
0.003991 --> 0.00399
0.3241 --> 0.324
1045.3491 --> 1,045.35
つまり、数値が「0」より大きい場合は、小数点以下2桁に丸めて、千の区切り記号(6,554.24など)を追加する必要があります。「1」より小さい場合は、数値がゼロの後に表示されるたびに3桁に丸める必要があります(たとえば、 0.0003219〜0.000322または0.2319〜0.232)
編集:同じことが「-」値にも当てはまるはずです。例えば:
-1024.43 --> -1,024.43
-0.000000931540 --> -0.000000932
-0.003991 --> -0.00399
-0.3241 --> -0.324
-1045.3491 --> -1,045.35
https://stackoverflow.com/a/48283297/2469308から適応
次のことを試してください。
function customRound($value)
{
if ($value > -1 && $value < 1) {
// define the number of significant digits needed
$digits = 3;
if ($value >= 0) {
// calculate the number of decimal places to round to
$decimalPlaces = $digits - floor(log10($value)) - 1;
} else {
$decimalPlaces = $digits - floor(log10($value * -1)) - 1;
}
// return the rounded value
return number_format($value, $decimalPlaces);
} else {
// simply use number_format function to show upto 2 decimal places
return number_format($value, 2);
}
// for the rest of the cases - return the number simply
return $value;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加