Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make number_format() not to round numbers up

Tags:

php

I have this number:

$double = '21.188624'; 

After using number_format($double, 2, ',', ' ') I get:

21,19 

But what I want is:

21,18 

Any ideea how can I make this work?

Thank you.

like image 546
Psyche Avatar asked Sep 30 '10 17:09

Psyche


People also ask

Does round () round up or down?

Rules for Rounding Here's the general rule for rounding: If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.

How can I get only 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Show activity on this post. This will give you 2 number after decimal.

How do I limit decimal places in PHP?

Parameter Values Specifies a constant to specify the rounding mode: PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2.


2 Answers

number_format will always do that, your only solution is to feed it something different:

$number = intval(($number*100))/100; 

Or:

$number = floor(($number*100))/100; 
like image 75
Wrikken Avatar answered Sep 20 '22 07:09

Wrikken


I know that this an old question, but it still actual :) .

How about this function?

function numberFormatPrecision($number, $precision = 2, $separator = '.') {     $numberParts = explode($separator, $number);     $response = $numberParts[0];     if (count($numberParts)>1 && $precision > 0) {         $response .= $separator;         $response .= substr($numberParts[1], 0, $precision);     }     return $response; } 

Usage:

// numbers test numberFormatPrecision(19, 2, '.'); // expected 19 return 19 numberFormatPrecision(19.1, 2, '.'); //expected 19.1 return 19.1 numberFormatPrecision(19.123456, 2, '.'); //expected 19.12 return 19.12 numberFormatPrecision(19.123456, 0, '.'); //expected 19 return 19  // negative numbers test numberFormatPrecision(-19, 2, '.'); // expected -19 return -19 numberFormatPrecision(-19.1, 2, '.'); //expected -19.1 return -19.1 numberFormatPrecision(-19.123456, 2, '.'); //expected -19.12 return -19.12 numberFormatPrecision(-19.123456, 0, '.'); //expected -19 return -19  // precision test numberFormatPrecision(-19.123456, 4, '.'); //expected -19.1234 return -19.1234  // separator test numberFormatPrecision('-19,123456', 3, ','); //expected -19,123 return -19,123  -- comma separator 
like image 24
ustmaestro Avatar answered Sep 21 '22 07:09

ustmaestro