Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Floating point rounding

Moderators: larsivi kris

Posted: 09/09/08 14:32:16

I would like to round a floating point to fewer digits, but I cannot find any functions for this.

Say I want to round 1.05 to one decimal and get 1.1. I don't want to first convert it to text and then back to a float :) I did a quick look at the tango.text.convert.Float format function, but it's a bit over my head to steal anything from there.

Is there something in the c runtime, or some other simple technique I can use?

Author Message

Posted: 09/09/08 17:12:56

In what circumstances would you want to round a float, but not print it or otherwise represent it as text? If you look in tango.math.Math, there are several round functions, but they all round to no decimals. The reason is that as long as you need decimals, you typically should calculate with as many as you have to keep up the precision.

Posted: 09/10/08 07:44:24

If you really want to do such a rounding one of very simple (but maybe not fast) techniques is to write function like this

float round_prec (float number , uint prec){
	auto mult = pow(cast(real)10, prec); 
	number = number * mult;
	number = round(number);
	number = number/ mult;
	return number;
}

Posted: 09/10/08 11:09:50

larsivi: I'm doing all calculations using max precision, but I'm showing the rounded down values and want a sum of the shown values.

piotrek: Thanks. It doesn't have to be fast as the bottleneck is, without a doubt, another piece of code.