sprintf() to truncate and not round a float to x decimal places?
When calculating a golf handicap differential you are supposed to truncate the answer to 1 decimal place without rounding. No idea why but...
I know how to do this using TRUNCATE() in mySQL
SELECT TRUNCATE( 2.365, 1 );
// outputs 2开发者_开发问答.3
but I was wondering if sprintf() could do this? The only way I know to work with decimal places in a float is ...
echo sprintf("%.1f", 2.365);
// outputs 2.4
What language is this in? Assuming it's C or one of its derivatives, and assuming you always want exactly one decimal place, and assuming your values are always non-negative, you can do this:
float val = 12.3456;
val = floor(val*10.0)/10.0;
sprintf("%.1f", val);
Is there a better way? Probably. This is just what comes to mind.
I find it easier to use string operations: let sprintf round to an extra significant digit, trim, then convert back to a float
function truncate_float(float $float, int $significantDigits = 4): float
{
$format = sprintf('%%.%df', $significantDigits + 1);
return (float) substr(sprintf($format, $float), 0, -1);
}
精彩评论