Jump to content

[SOLVED] show 2 digit of decimal


asmith

Recommended Posts

hey guys

 

i want to show number which have more than 2 decimal to a 2 decimal form but not rounding or floor  like:

 

2.234 =>  2.23

54.73453 => 54.73

1.1 = > 1.1

4.56 => 4.56

45.53218753 => 45.53

12362.534 => 12362.53

 

what is the simplest way to do such thing ?

 

i've tried money_format , but it rounds the number and can't be run in windows, only on linux servers .

 

i was thinking about treat the number as a string, explode it with " . " , then count the digits after "." .  and substr it to 2 digits . but it is way too much coding for a simple purpose .

 

any better idea ?

 

thanks

Link to comment
Share on other sites

Because they don't do the same?

 

number_format('1000.568', 2); // 1,000.57
round('1000.568', 2); // 1000.57

 

if you don't need the thousands comma, no problem:

<?php
echo number_format('1000.568', 2, '', '.'); // 1000.57

Link to comment
Share on other sites

<?php
class Timer
{
private $start_time;

function __construct()
{
	$this->start_time = microtime();
}

public function getTime()
{
	$start_time	= explode(' ', $this->start_time);
	$stop_time	= explode(' ', microtime());

	$start_time	= $start_time[0] + $start_time[1];
	$stop_time	= $stop_time[0] + $stop_time[1];

	return $stop_time - $start_time;
}
}

$float = 1168168.681681;
$precision = 2;
$operations = 100000;

$timer = new Timer();
for($i = 0; $i < $operations; $i++)
{
$new_num = round($float, $precision);
}
$round_time = $timer->getTime();
echo "round: {$round_time}\n";

$timer = new Timer();
for($i = 0; $i < $operations; $i++)
{
$new_num = number_format($float, $precision, '.', '');
}
$number_format_time = $timer->getTime();
echo "number_format: {$number_format_time}\n";
?>

Output:

round: 0.2045259475708

number_format: 0.69444394111633

 

round() is around 3.4 times faster.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.