What is the JS equivalent to the PHP function number_format?
is this what you'd like to get?
yourFloatVarHere.toFixed(2);
voilà. number_format function of php and calculate with js
Show the formatted number but echo the unformatted number elsewhere and use that in js. For example:
PHP
<div id="number" data-myvalue="<?=$number?>"><?=number_format($number)?></div>
JAVASCRIPTvar myvalue = $("#number").data("myvalue");
What is the exact equivalent of JS: something.toFixed() in PHP?
I found that sprintf
and number_format
both round the number, so i used this:
$number = 2.4232;
$decimals = 3;
$expo = pow(10,$decimals);
$number = intval($number*$expo)/$expo; // = 2423/100
Number Format in Javascript + conversion?
Use toFixed()
method of float:
var ttc_txt = parseFloat(ttc_val).toFixed(2);
Returns something like "123.00"
You can use it as string. If you need a strict type string, just add
+""
to expression:var ttc_txt = parseFloat(ttc_val).toFixed(2)+"";
Is there a PHP function equivalent to JavaScript function toLocaleString()
PHP does allow for Number Formatting, but does not have a function that can do exactly as Javascript's toLocaleString().
The best equivelant is provided here: How to display Currency in Indian Numbering Format in PHP
PHP's NumberFormatter can be used to format decimals. The JavaScript implementation sets the locale value on the client side of the browser and then outputs the results.
PHP has a similar method for setting the locale value, but is performed on the server. This could result in unintended consequences.
"Warning: The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale()." Source: http://php.net/manual/en/function.setlocale.php
NumberFormatter in PHP vs NumberFormat in JS
I tried this approach:
<?php
function process($locale, $value, $currency){
$fmt = numfmt_create($locale, NumberFormatter::CURRENCY );
echo "Locale: $locale, Currency: $currency, Result: " . $fmt->formatCurrency($value, $currency) . "\n";
}
$locales = ["tl_PH","fil_PH", "en_US"];
$currencies = ["USD", "PHP"];
$value = 5125.99;
foreach ($locales as $locale){
foreach ($currencies as $currency){
process($locale, $value, $currency);
}
}
and got consistent results:Locale: tl_PH, Currency: USD, Result: $5,125.99
Locale: tl_PH, Currency: PHP, Result: ₱5,125.99
Locale: fil_PH, Currency: USD, Result: $5,125.99
Locale: fil_PH, Currency: PHP, Result: ₱5,125.99
Locale: en_US, Currency: USD, Result: $5,125.99
Locale: en_US, Currency: PHP, Result: PHP 5,125.99
Thus, to be 100% safe, I would suggest creating a small server side component for the formatting purposes, so that you can pass the locale, value and currency and always have the same result regardless if it's backend or frontend that needs the formatted string.Also, note that tl-PH
and tl_PH
is not the same. Use tl_PH
and fil_PH
and en_US
consistently.
Parameter passing from JavaScript to PHP
Instead of formatting your data in the view file, format your data in controller and then send it to view. So you can use the formatted data directly.
Change your controller code to following:
public function addStock(Request $request) {
$data = new ShoppingCartDetail();
$data->cart_id = $request->input('cart_id');
$data->stock_id = $request->input('stock_id');
$data->price = 1;
$data->save();
$data->x = 4;
$data->price = 1200;
$formattedPrice = number_format($data->x * $data->price, '2' , ',', '.');
return response()->json(["data" => $data, 'formattedPrice' => $formattedPrice]);
}
You can then use the new "formattedPrice":$('#5').replaceWith("<span class='para fw6'>" + data.formattedPrice + "TL</span>");
Replicate number_format
Here's a working version of Kae Verens' function.
function number_format($num){
$num=(string)$num;
$len=strlen($num);
$newnum='';
for ($i=0; $i<$len; ++$i) {
if (($i%3==0) && $i) {
$newnum=','.$newnum;
}
$newnum=$num[$len-$i-1].$newnum;
}
return $newnum;
}
Related Topics
The Behaviour of the or Operator in PHP
Moving Array Element to Top in PHP
Rounding Up to the Second Decimal Place
Type Hinting: Default Parameters
PHP Curl: Curlopt_Connecttimeout VS Curlopt_Timeout
How to Automatically Read in Calculated Values with PHPexcel
How to Use Laravel Passport with a Custom Username Column
Use PHP to Check If Page Was Accessed with Ssl
How to Put Double Quotes Inside a String Within an Ajax JSON Response from PHP
How to Refresh Select2 Dropdown Menu After Ajax Loading Different Content
How to Select a MySQL Database to Use with Pdo in PHP
Phpmyadmin Failed to Set Session Cookie. Maybe You Are Using Http Instead of Https