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 ?
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 ?
Multiply by 100, take floor() of the number, divide by 100 again.
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.
You should be able to get what you want like this:
number.ToString("#0.00")
This doesn't work?
double d = 1234.5678;
double rounded =Math.Round(d, 2);
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).
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);
This should do the trick.
string rawVal = "1234.5678";
System.Math.Floor((double.parse(rawVal)) * 100) / 100;