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
https://forums.phpfreaks.com/topic/87344-solved-show-2-digit-of-decimal/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.