この型キャストを行うとき:
(float) '0.00';
取得し0
ます。0.00
データ型をfloatとして取得し、保持するにはどうすればよいですか?
0
floatにはorがありません。これらは、内部(IEEE754)バイナリ形式の0.00
異なる文字列表現ですが、floatは同じです。
floatを「0.00」として表現する場合は、number_formatを使用して文字列にフォーマットする必要があります。
$numberAsString = number_format($numberAsFloat, 2);
私の知る限り、これを修正するPHPの解決策はありません。このスレッドで与えられた他のすべての(上と下の)答えはナンセンスです。
number_format関数は、PHP.net独自の仕様で記述された結果として文字列を返します。
floatval / doublevalのような関数は、値3.00を指定すると、整数を返します。
タイプジャグリングを行うと、結果として整数が得られます。
round()を使用すると、結果として整数が得られます。
私が考えることができる唯一の可能な解決策は、floatへの型変換にデータベースを使用することです。たとえばMySQL:
SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;
文字列の代わりにfloatを返す抽象化レイヤーを使用してこれを実行すると、そこに行きます。
JSON出力を修正して小数点以下2桁を保持するソリューションを探している場合は、次のコードのようにポストフォーマットを使用できます。
// PHP AJAX Controller
// some code here
// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);
// output to browser / client
print $json;
exit();
クライアント/ブラウザに戻ります:
{"x":"y","price":0.00}
0.00は実際には0です。エコーするときに0.00が必要な場合は、次のようにnumber_formatを使用します。
number_format($number, 2);
フロート番号を表示できます
すなわち
$myNonFormatedFloat = 5678.9
$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90
$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90
注意してください、
最初の引数は、フォーマットする浮動小数点数です
2番目の引数は小数点以下の桁数です
3番目の引数は、小数点以下を視覚的に区切るために使用される文字です。
4番目の引数は、数千を視覚的に分離するために使用される文字です
number_format()
この関数を使用して、数値の表示方法を変更します。を返しstring
ます。元の変数の型は影響を受けません。
あなたはこれを試すことができます、それはあなたのために働きます
number_format(0.00, 2)
これを試して
$nom="5695.5";
number_format((float)($nom), 2, '.', ','); // -> 5,695.50
$nom="5695.5215";
number_format((float)($nom), 2, '.', ','); // -> 5,695.52
$nom="5695.12";
number_format((float)($nom), 0, '.', ','); // -> 5,695
使用できますfloatval()
ラウンド関数を使用できます
round("10.221",2);
10.22を返します
これを試して
$result = number_format($FloatNumber, 2);
float値をフォーマットすると、そのデータ型が文字列に変更されることを意味します。したがって、任意の量/フロート値にフォーマットを適用すると、ドット、コンマなどのすべての可能な表記で設定されます。たとえば、
(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'
したがって、論理的には、フォーマット後にfloatデータ型を保持することはできません。
この簡単な関数を使用できます。 number_format()
$num = 2214.56;
// default english notation
$english_format = number_format($num);
// 2,215
// French notation
$format_francais = number_format($num, 2, ',', ' ');
// 2 214,56
$num1 = 2234.5688;
// English notation with thousands separator
$english_format_number = number_format($num1,2);
// 2,234.57
// english notation without thousands separator
$english_format_number2 = number_format($num1, 2, '.', '');
// 2234.57