www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - rounding floats up to specified number of decimal digits

reply "ref2401" <refactor24 gmail.com> writes:
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?
Dec 15 2013
parent "John Colvin" <john.loughran.colvin gmail.com> writes:
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
Dec 15 2013