Dim number = 5.678
Console.WriteLine(number.ToString("#,##0.##"))
displays 5.68
. Is there any number format string without rounding it?
UPDATE: desired result is 5.67
Dim number = 5.678
Console.WriteLine(number.ToString("#,##0.##"))
displays 5.68
. Is there any number format string without rounding it?
UPDATE: desired result is 5.67
Console.Write(Math.Truncate(number * 100) / 100);
This should work. Read more answers here
If you always have to truncate till 2 places, you can use:
Console.WriteLine("{0:F2}", number - 0.005);
Otherwise you can change number '0.005' as per your need.
Update: If you want to treat this as string, I don't think there is any readymade solution in C#, so you might have to do some extra work like below(You can create a helper method):
const double number = 5.678; //input number
var split = number.ToString(CultureInfo.InvariantCulture).Split('.');
Console.WriteLine(split[0] + (split.Length > 1 ? "." : "") + (split.Length > 1 ? split[1].Substring(0, split[1].Length > 1 ? 2 : split[1].Length) : ""));
Input: 5.678; Output: 5.67;
Input: 5.6325; Output: 5.63;
Input: 5.64; Output: 5.64
Input: 5.6; Output: 5.6;
input: 585.6138 output: 585.61
I'm really surprised that not default functionality. This is basically ATP answer except his puts commas between the thousands place.
int precision = 2;
string format = "0.##";
decimal rounder = 5.0m/(decimal) Math.Pow(10, precision + 1);
var result = (5.678m - rounder).ToString(format); // This doesn't work for a value of 0m
One line:
result = (5.678m - 5.0m / (decimal)Math.Pow(10, 2 + 1)).ToString("0.##");