Delete digits after two decimal points, without rounding the value
TL;DR:
The PHP native function bcdiv seems to do precisely what is required, and properly.
To simply "truncate" a number, bcdiv($var, 1, 2);
where 2 is the number of decimals to preserve (and 1 is the denomenator - dividing the number by 1 allows you to simply truncate the original number to the desired decimal places)
Full Answer (for history)
This turns out to be more elusive than one might think.
After this answer was (incorrectly) upvoted quite a bit, it has come to my attention that even sprintf will round.
Rather than delete this answer, I'm turning it into a more robust explanation / discussion of each proposed solution.
number_format - Incorrect. (rounds)
Try using number format:
$var = number_format($var, 2, '.', ''); // Last two parameters are optional
echo $var;
// Outputs 2.50
If you want it to be a number, then simply type-cast to a float:
$var = (float)number_format($var, 2, '.', '');
Note: as has been pointed out in the comments, this does in fact round the number.
sprintf - incorrect. (sprintf also rounds)
If not rounding the number is important, then per the answer below, use sprintf:
$var = sprintf("%01.2f", $var);
floor - not quite! (floor rounds negative numbers)
floor, with some math, will come close to doing what you want:
floor(2.56789 * 100) / 100; // 2.56
Where 100 represents the precision you want. If you wanted it to three digits, then:
floor(2.56789 * 1000) / 1000; // 2.567
However, this has a problem with negative numbers. Negative numbers still get rounded, rather than truncated:
floor(-2.56789 * 100) / 100; // -2.57
"Old" Correct answer: function utilizing floor
So a fully robust solution requires a function:
function truncate_number( $number, $precision = 2) {
// Zero causes issues, and no need to truncate
if ( 0 == (int)$number ) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
Results from the above function:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
New Correct Answer
Use the PHP native function bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
Delete digits after two decimal point without rounding its value in flutter?
If you want to round the number:
var num1 = 10.12345678;
var num2 = double.parse(num1.toStringAsFixed(2)); // num2 = 10.12
If you do NOT want to round the number:
Create this method:
double getNumber(double input, {int precision = 2}) =>
double.parse('$input'.substring(0, '$input'.indexOf('.') + precision + 1));
Usage:
var input = 113.39999999999999;
var output = getNumber(input, precision: 1); // 113.9
var output = getNumber(input, precision: 2); // 113.99
var output = getNumber(input, precision: 3); // 113.999
Truncate number to two decimal places without rounding
Convert the number into a string, match the number up to the second decimal place:
function calc(theform) { var num = theform.original.value, rounded = theform.rounded var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0] rounded.value = with2Decimals}
<form onsubmit="return calc(this)">Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /><br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly></form>
Drop decimal place without rounding value
You're trying to round a negative number. Rounding down a negative number with floor()
will increase its absolute value; remember, -23.43(0)
is less than -23.425
!
Instead, you're looking to round up its value with ceil()
:
echo ceil(-23.425 * 100) / 100; // -23.42
This can be seen working here.
Truncate Two decimal places without rounding
value = Math.Truncate(100 * value) / 100;
Beware that fractions like these cannot be accurately represented in floating point.
Remove decimal places to certain digits without rounding
My solution involving int
abuse. int
rounds towards the nearest 0. I multiply it by 10**3
to affect rounding. After using int
, I divide it by 10**3
to get actual results.
It's safer, as it does work with e
notation.
int(15.55555 * 10**3) / 10.0**3
How to remove trailing decimals without rounding up?
var number = parseInt('' + (num * 100)) / 100;
Related Topics
How to Resolve a Http 414 "Request Uri Too Long" Error
Laravel Eloquent Sum of Multiplied Columns
Laravel Convert Query MySQL to Model Query
How to Remove Query Part from $Request->All() in Laravel Framework
Php: How to Detect If a Session Has Expired Automatically
How to Add Class to Link in Wp_Nav_Menu
How to Pass Something With Apostrophe to Json
Reference - Frequently Asked Questions About Pdo
What Is the Easiest Way to Check If Time Is Set in Datetime Variable
Remove License Check from Script Code in Codeigniter
How to Get Values of Checkbox Array in Laravel 5
How to Update Stock Quantity Using MySQL in PHP
Combining 'Where' and 'Like' Statements by Using the Ci Activerecords