tags:

views:

442

answers:

7

Hi

I have this number: 1234.5678 (as a text)

I need this number as double, with only 2 numbers after the dot

But without Round the number

in 1234.5678 - i get 1234.57

in 12.899999 - i get 12.90

How I can do it ?

+1  A: 

Multiply by 100, take floor() of the number, divide by 100 again.

Charlie Martin
+1  A: 

This is because you can't represent these numbers exactly as doubles, so converting, rounding, and then reprinting as text results in a loss of precision.

Use 'decimal' instead.

Aric TenEyck
NO, he's concerned with truncating rather than rounding. That doesn't have anything to do with the internal representation.
Charlie Martin
+4  A: 

You should be able to get what you want like this:

number.ToString("#0.00")
Jeremy
never used the pound sign thing. is that the part that controls rounding?
Jared Updike
@Jared: No, it an optional digit in a picture mask.
Henk Holterman
A: 

This doesn't work?

  double d = 1234.5678;
  double rounded =Math.Round(d, 2);
Jeff Meatball Yang
A: 

Take this floating point arithmetic!

var num = "1234.5678";
var ans = String.Empty;
if( !String.IsNullOrEmpty(num) && num.Contains('.') ) // per comment
{
  ans = num.Substring(0, num.IndexOf('.') + 3);
}

(This code carries no warranties express or implied).

JP Alioto
you could at least add the checks for not-exists and end-of-string :>
Jimmy
+3  A: 

You didn't post the results you wanted, but I assume you want truncation, so that you'll see 1234.56, and 12.89. Try:

decimal d = 1234.89999M;
Console.WriteLine(Math.Truncate(d * 100) / 100);
Michael Petrotta
+1  A: 

This should do the trick.

string rawVal = "1234.5678";
System.Math.Floor((double.parse(rawVal)) * 100) / 100;
James