Main Site Documentation

Round/Truncate a double to 2 decimal places


#1

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.


#2

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)


#3

MathEx.Truncate(a*100)/100 ?

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


#4

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


#5

Nope, still goes nuts.

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


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

#7

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


#8

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


#9

Yeah, that’s what I meant.


#10

have you try this

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

result: “987.65”


#11

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


#12

@ Sam: There is no String.Format()


#13

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

For sure it is in .NET Framework 4

http://msdn.microsoft.com/en-us/library/system.string.format.aspx

:-[


#14

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


#15

+1. Pretty please?


#16

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


#17

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


#18

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


#19

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


#20

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?