rounding floats up to specified number of decimal digits

John Colvin john.loughran.colvin at gmail.com
Sun Dec 15 06:53:40 PST 2013


On Sunday, 15 December 2013 at 14:35:04 UTC, ref2401 wrote:
> I'm seeking for a way to round floats up to specified number of 
> decimal digits. e.g. roundToDigits(3.1415, 2) should return 
> 3.14.
> Is there a standard function for that or what is the most 
> correct way to do that?

You can quite easily write a function like this:

auto roundToDigits(T x, uint numDigits)
{
     auto s = 10 ^^ numDigits;
     return round(s * x) / s;
}

but it will introduce a certain amount of error* as IEE 754 uses 
base-2, making the multiplation and division inexact. It's 
probably good enough for some purposes, but take care.

If you just want to print out to a particular precision then use 
std.format/std.stdio


More information about the Digitalmars-d-learn mailing list