rounding floats up to specified number of decimal digits

2013-12-15 Thread ref2401
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?


Re: rounding floats up to specified number of decimal digits

2013-12-15 Thread John Colvin

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