Reputation: 62554
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 ?
Upvotes: 0
Views: 4674
Reputation: 45127
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);
}
Upvotes: 1
Reputation: 12806
This should do the trick.
string rawVal = "1234.5678";
System.Math.Floor((double.parse(rawVal)) * 100) / 100;
Upvotes: 1
Reputation: 60972
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);
Upvotes: 3
Reputation: 39057
This doesn't work?
double d = 1234.5678;
double rounded =Math.Round(d, 2);
Upvotes: -1
Reputation: 6680
You should be able to get what you want like this:
number.ToString("#0.00")
Upvotes: 5
Reputation: 8032
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.
Upvotes: 1
Reputation: 112424
Multiply by 100, take floor() of the number, divide by 100 again.
Upvotes: 3