Round/Truncate a double to 2 decimal places

Anybody have any good ideas on this one? Mark and I have tried a few things, and nothing seems to work.

Basically, I want something like this:
4.9999999999555
To go to this:
4.99

Rounding would also work.

Couldent you first convert the double to a string via the ToString(F2) and then convert it back in to a double?
(Im at work so I have no access to my stuff to test it out)

MathEx.Truncate(a*100)/100 ?

Can’t check, though, without a board :wall:

I thought i sorted Chris out with this on chat :stuck_out_tongue: The value is correct in memory but tostring goes stupid.

Nope, still goes nuts.

Yikes. this might work, but god, that would be messy as hell.

double truncated = ((int) (d*100.0))/100.0;

I ended up just using toString("F2) I’m printing the data anyway, so it’s not a big issue. Nothing else works.

well the others work fine, just not for outputting with .ToString() :stuck_out_tongue:

Yeah, that’s what I meant.

have you try this

String.Format("{0:0.00}", 987.65432);   

result: “987.65”

I have to try it but in c I do this

(float)((int)(4.9999999995 * 100) / 100)

If you don’t cast it to an int it will never change
I then cast it back AFTER loosing what I dont need.

Regards Ian

@ Sam: There is no String.Format()

Chris,
May be not in .NET MF ???

For sure it is in .NET Framework 4

[url]Microsoft Learn: Build skills that open doors in your career

:-[

Yeah it’s not in netmf… and i miss it :frowning: Perhaps GHI could implement it for us?

+1. Pretty please?

Maybe we should post in the suggestions forum… at least this one isn’t Josh’s job

Why is this not wokring?
MathEx.Truncate(a*100)/100
What values did you get?

No matter what, the value was always toString()'ing out with too many decimal places, even if the number was correct in the locals.

I believe it’s an error in ToString because if you interrogate the variable while debugging in visual studio it has the correct value.

Isnt this just an academicals problem as the floating point variable always will be stored as an approximation of the value. As long as we have the modifier on .ToString(F2) does it really matter that the .ToString() doesnt give the same readout?