How to get two digits after decimal point?
![Two digit after decimal point](https://www.infotechnicians.com/wp-content/uploads/2022/12/Two-20digits-20after-20decimal.png)
Hey Info Technicians…
This may help you to obtain only two digits after decimal point.
I’ve written this code in C#. And this will not round the values(I hate it in this situation)
Two digits after decimal point using Double data type
If you’re using Double data type,
C#
public static double ReturnTwoDigits(double fullValue)
{
if (fullValue.ToString().Contains("."))
{
string[] split = fullValue.ToString().Split('.');
if (split[1].Length <= 1)
{
string afterPoint = split[1].Substring(0, 1);
string fullAmount = split[0] + "." + afterPoint;
fullValue = System.Convert.ToDouble(fullAmount);
return Math.Abs(fullValue);
}
var elseAfterPoint = split[1].Substring(0, 2);
string elseFullAmount = split[0] + "." + elseAfterPoint;
fullValue = System.Convert.ToDouble(elseFullAmount);
return Math.Abs(fullValue);
}
return Math.Abs(fullValue);
}
Here I’ve used Math.Abs() method to get only positive values.
If you don’t want you can remove that.
Also you can use this in your string values.
For example, you can use the below to work with string values,
Two digits after decimal point using string data type
C#
public static string ReturnTwoDigits(string fullValue)
{
if (fullValue.Contains("."))
{
string[] split = fullValue.Split('.');
if (split[1].Length <= 1)
{
string afterPoint = split[1].Substring(0, 1);
string fullAmount = split[0] + "." + afterPoint;
return fullAmount;
}
var elseAfterPoint = split[1].Substring(0, 2);
string elseFullAmount = split[0] + "." + elseAfterPoint;
return elseFullAmount;
}
return fullValue;
}
In this, you can add conditions too like if there’s no value after a decimal point you can add that also.
Please share your comments and feedback below.