While writing programs sometimes we will come across to display decimal number with specific precisions only even if we are getting decimal number with more number of precisions.
Suppose a scenario where I am getting decimal value from database or some where else like 100.456789 and i want to display this as 100.456 by truncating last 789 digits on my UI.
So here if we apply Math.Round() function for 3 decimal places then that will round decimal number like 100.457. here 7 is greater than 5 so it will add one in adjacent. If i don't want to be added that number to its adjucent then I have to go for truncate numbers.
So this can be achieved in two ways:
1. Math.Truncate function.
2. String Formatting.
1. Using Math.Truncate() function:
decimal inputNumber = 100.456789;
decimal truncatedNumber = Math.Truncate(inputNumber*1000)/100;
these line of code will give us 100.456
2. Using String Formatting:
if(inputNumber.ToString().Contain('.'))
{
string[] inputArr = inputNumber.ToString();
if(inputArr.Length==2)
{
if(inputArr[1].Length > 3)
{
string output = inputNumber.ToString().Substring(0, inputNumber.ToString().LastIndexOf(".").Length + 3);
//now here we just need to convert string number to decimal type something like below
decimal returnValue = decimal.Parse(string.Format("{0:0.###}", output));
}
}
}
I hope this code snippet will be helpful.....
Suppose a scenario where I am getting decimal value from database or some where else like 100.456789 and i want to display this as 100.456 by truncating last 789 digits on my UI.
So here if we apply Math.Round() function for 3 decimal places then that will round decimal number like 100.457. here 7 is greater than 5 so it will add one in adjacent. If i don't want to be added that number to its adjucent then I have to go for truncate numbers.
So this can be achieved in two ways:
1. Math.Truncate function.
2. String Formatting.
1. Using Math.Truncate() function:
decimal inputNumber = 100.456789;
decimal truncatedNumber = Math.Truncate(inputNumber*1000)/100;
these line of code will give us 100.456
2. Using String Formatting:
if(inputNumber.ToString().Contain('.'))
{
string[] inputArr = inputNumber.ToString();
if(inputArr.Length==2)
{
if(inputArr[1].Length > 3)
{
string output = inputNumber.ToString().Substring(0, inputNumber.ToString().LastIndexOf(".").Length + 3);
//now here we just need to convert string number to decimal type something like below
decimal returnValue = decimal.Parse(string.Format("{0:0.###}", output));
}
}
}
I hope this code snippet will be helpful.....