diff --git a/src/TerminalObject/Dynamic/Progress.php b/src/TerminalObject/Dynamic/Progress.php index e673eda..73516c8 100644 --- a/src/TerminalObject/Dynamic/Progress.php +++ b/src/TerminalObject/Dynamic/Progress.php @@ -27,6 +27,13 @@ class Progress extends DynamicTerminalObject */ protected $current_percentage = ''; + /** + * The number of decimal points to display + * + * @var integer $precision + */ + protected $precision = 0; + /** * The string length of the bar when at 100% * @@ -88,6 +95,20 @@ public function total($total) return $this; } + /** + * Set the completed percentage precision + * + * @param integer $precision The number of decimal places to display + * + * @return Progress + */ + public function precision($precision) + { + $this->precision = $precision; + + return $this; + } + /** * Determines the current percentage we are at and re-writes the progress bar * @@ -281,12 +302,14 @@ protected function getBarStrLen() /** * Format the percentage so it looks pretty * - * @param integer $percentage + * @param integer $percentage The percentage (0-1) to format + * * @return float */ protected function percentageFormatted($percentage) { - return round($percentage * 100) . '%'; + $factor = pow(10, $this->precision); + return round($percentage * 100 * $factor) / $factor . '%'; } /** diff --git a/tests/ProgressTest.php b/tests/ProgressTest.php index 91990d8..157787d 100644 --- a/tests/ProgressTest.php +++ b/tests/ProgressTest.php @@ -84,6 +84,32 @@ public function it_can_output_a_progress_bar_via_constructor() } } + /** + * @test + * @doesNotPerformAssertions + */ + public function it_can_output_a_progress_bar_with_precision() + { + $this->shouldWrite(''); + $this->shouldWrite("\e[m\e[1A\r\e[K{$this->repeat(0)} 0.008%\e[0m"); + $progress = $this->cli->progress(100000); + $progress->precision(3); + $progress->current(8); + } + + /** + * @test + * @doesNotPerformAssertions + */ + public function it_can_output_a_progress_bar_with_precision_rounded() + { + $this->shouldWrite(''); + $this->shouldWrite("\e[m\e[1A\r\e[K{$this->repeat(0)} 0.01%\e[0m"); + $progress = $this->cli->progress(100000); + $progress->precision(2); + $progress->current(8); + } + /** * @test * @doesNotPerformAssertions