How to add precision to decimal value - c#

I want to add precision to the decimal value. For example, I have this value:
decimal number = 10;
I want to make it 10.00. I don't want to convert it to string like number.ToString("#.00")
Currently, I have this method:
decimal CalculatePrecision(decimal value, int precision)
{
var storedCalculated = decimal.Divide(1, Convert.ToDecimal(Math.Pow(10, precision)));
return value + storedCalculated - storedCalculated;
}
Is there any good solution for this?

You can't. 10 and 10.00 are the same number. Only the "presentation" is different. Both "presentations" are strings. The actual number look different. If you need to change the presentation, convert to string.

How about
decimal d = 10;
d += 0.00M;
Console.WriteLine(d);
Try reference
Math.Round not keeping the trailing zero
How do I display a decimal value to 2 decimal places?

Related

Convert decimal with comma and floating point

i want to parse like:
3.5 -> 3.5
3.484 -> 3.48
3.82822 -> 3.82
etc.
However,
decimal.Parse("3.543")
yields 3543 and
so i did:
decimal.Parse("3.543",CultureInfo.InvariantCulture)
yields 3.543 and
but
decimal.Parse(String.Format("{0:0.00}","3.543"),CultureInfo.InvariantCulture);
yields 3543
so how can i do it???
You need Round method:
decimal t = 3.82822;
decimal.Round(t, 2);
Where 2 show the decimal points you need.
Use Math.Round like this:
decimal a = 1.9946456M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.9953454M;
Math.Round(b, 2); //returns 2.00
I guess you want to truncate the decimal places after two digits. Give this a try:
public decimal TruncateDecimal(decimal value, int precision)
{
decimal step = (decimal)Math.Pow(10, precision);
int tmp = (int)Math.Truncate(step * value);
return tmp / step;
}
decimal t = 3.82822;
decimal d = TruncateDecimal(t, 2);
You should use a culture that actually uses a comma as a decimal seperator.
CultureInfo.GetCultureInfo("fr-fr")
for example.
Console.WriteLine(decimal.Parse("3,543", CultureInfo.InvariantCulture)); // 3543
Console.WriteLine(decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr"))); //3,543
and if you want to round the result. You could use
Console.WriteLine(String.Format("{0:0.00}", decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr")))); //3,54

Get net vat values the vat value in C#

I need to get the net values (vat #20%) of wallet and paper as below, added together
{
this.transaction.netValue = Math.Round(Convert.ToDecimal(wallet) + Convert.ToDecimal(paper), 2);
}
and then to get the vat value (20%) having established the net values of both wallet and paper
{
transaction.vatAmount = Round(Convert.ToDecimal(wallet) + Convert.ToDecimal(paper), 2);
}
I know how to do the formulas in excel, but having difficulty in c#
Updated
this.transaction.netValue = Math.Round(Convert.ToDecimal([wallet]/1.2m) + Convert.ToDecimal([paper]/1.2m), 2);
Convert to decimal first then divide by 1.2m
You are seeing squiggly lines because your are trying to divide two different types of datatypes. first your're converting wallet to decimal and then you're dividing it with 1.2 which is double and you need to change it to decimal as well. From decimal (C# Reference)
If you want a numeric real literal to be treated as decimal, use the
suffix m or M. Without the suffix m, the number is treated as a double
and generates a compiler error.
So your final code will be something as follows
this.transaction.netValue = Math.Round(Convert.ToDecimal(wallet) / 1.2m + Convert.ToDecimal(paper) / 1.2m, 2);
Assuming that the values in wallet and paper strings are actually valid decimal numbers then you need to apply
decimal totalValue = Convert.ToDecimal(wallet) +
Convert.ToDecimal(paper);
decimal netValue = totalValue / 1.2m;
this.transaction.netValue = Math.Round(netValue, 2);
Do not put square brackets around the string and do not put the division inside the parameter (a string is required) that you pass to Convert.ToDecimal
Of course this could be written in a single line but because you are recalculating again that netValue for vatAmount then using a temporary variable is better because you can reuse it for the subsequent calculation
(By the way vatAmount = totalValue - netValue, right? )
Instead if your inputs are not guaranteed to be correct decimal values then you should use decimal.TryParse
decimal walletValue;
decimal paperValue;
if(!decimal.TryParse(wallet, out walletValue))
{
MessageBox.Show("Not a valid decimal value for wallet");
return;
}
if(!decimal.TryParse(paper, out paperValue))
{
MessageBox.Show("Not a valid decimal value for paper");
return;
}
decimal totalValue = walletValue + paperValue;
decimal netValue = totalValue / 1.2m;
this.transaction.netValue = Math.Round(netValue, 2);
this.transaction.vatValue = Math.Round(totalValue - vatValue, 2);

Truncate Timespan after two decimal places

I have a timespan that displays as such: 7.43053333333333. My goal is to simply display it as 7.43.
How would I truncate two the second value after the decimal place. I tried using Math.Round instead of truncating, but it would simnple return 7
Just use Math.Round Method (Decimal, Int32)
double d = 7.43053333333333;
double ma = Math.Round(d, 2);
Use Math.Round and supply number of digits to round
double roundedValue = Math.Round(7.43053333333333, 2);
You will get back 7.43
How would I truncate two the second value after the decimal place.
if you just want to truncate the double value to get 2 digits after precision.
Try This:
double d = 7.43053333333333;
String s = d.ToString("N2");
use Math.Round() like following
Math.Round(7.43053333333333, 2);

C# convert round up textbox

I have a text box where I can enter numeric data which I can have decimals up to two decimal places, example 125.02 or just 125. However, I want to round all data that is entered with a decimal up, example 125.55 would equal 126. Below is a snippet of my broken code. Any suggestions would be great!
int num6 = (int)Math.Ceiling(textBox5.Text);
I think you need to covert the string to a double. Try this:
int num6 = (int)Math.Ceiling(double.Parse(textBox5.Text));
or safer to use double.TryParse:
int num6;
double d;
if(double.TryParse(textBox5.Text, out d)
{
num6 = (int)Math.Ceiling(d);
} else {
//Bad input value - perhaps flag this to user
}
Math.Ceiling method has 2 overloads;
Math.Ceiling Method (Double)
Math.Ceiling Method (Decimal)
It doesn't have an overload takes string as a parameter. You need to parse your string like;
decimal d;
if(Decimal.TryParse(textBox5.Text, out d))
{
int num6 = (int)Math.Ceiling(d);
}

Decimal ToString() conversion issue in C#

I am facing a problem when I try to convert decimal? to string. Scenario is
decimal decimalValue = .1211;
string value = (decimalValue * 100).ToString();
Current Result : value = 12.1100
Expected Result : value = 12.11
Please let me know, what could be reason for this.
Decimal preserves any trailing zeroes in a Decimal number. If you want two decimal places instead:
decimal? decimalValue = .1211m;
string value = ((decimal)(decimalValue * 100)).ToString("#.##")
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
or
string value = ((decimal)(decimalValue * 100)).ToString("N2")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
From System.Decimal:
A decimal number is a floating-point
value that consists of a sign, a
numeric value where each digit in the
value ranges from 0 to 9, and a
scaling factor that indicates the
position of a floating decimal point
that separates the integral and
fractional parts of the numeric value.
The binary representation of a Decimal
value consists of a 1-bit sign, a
96-bit integer number, and a scaling
factor used to divide the 96-bit
integer and specify what portion of it
is a decimal fraction. The scaling
factor is implicitly the number 10,
raised to an exponent ranging from 0
to 28. Therefore, the binary
representation of a Decimal value is
of the form, ((-296 to 296) / 10(0 to
28)), where -296-1 is equal to
MinValue, and 296-1 is equal to
MaxValue.
The scaling factor also preserves any
trailing zeroes in a Decimal number.
Trailing zeroes do not affect the
value of a Decimal number in
arithmetic or comparison operations.
However, >>trailing zeroes can be
revealed by the ToString method if an
appropriate format string is applied<<.
Remarks:
the decimal multiplication needs to be casted to decimal, because Nullable<decimal>.ToString has no format provider
as Chris pointed out you need to handle the case that the Nullable<decimal> is null. One way is using the Null-Coalescing-Operator:
((decimal)(decimalValue ?? 0 * 100)).ToString("N2")
This article from Jon Skeet is worth reading:
Decimal floating point in .NET (seach for keeping zeroes if you're impatient)
Since you using Nullable<T> as your decimal, Nullable<T>.ToString() method doesn't have overloading takes parameters that you can use for formatting.
Instead of, you can explicitly cast it to decimal and you can use .ToString() method for formatting.
Just use "0.00" format in your .ToString() method.
decimal? decimalValue = .1211M;
string value = ((decimal)(decimalValue * 100)).ToString("0.00");
Console.WriteLine(value);
Output will be;
12.11
Here is a DEMO.
As an alternative, you can use Nullable<T>.Value without any conversation like;
string value = (decimalValue * 100).Value.ToString("0.00");
Check out for more information from Custom Numeric Format Strings
Alternatively, you can specify the format "F2", like so: string val = decVal.ToString("F2") as this specifies 2 decimal places.
Use the fixed-point ("F) format specifier .
string value = (decimalValue * 100).ToString("F");
The default precision specifier is based on value of NumberFormatInfo.NumberDecimalDigits property which by default has value 2. So if don't specify a digit aftyer "F" , it by default specifies two decimal digits.
F0 - No decimal places
F1 - One decimal place
In case you do not want to limit to a certain amount of decimal digits:
decimal? decimalValue = .1211;
string value = decimalValue == null
? "0"
: decimalValue == 0
? "0"
: (decimalValue * 100).ToString().TrimEnd('0');
This will trim any (if any) trailing zeroes of the string and also return "0" if decimalValue is null. If the value is 0 then "0" is returned without trimming.
String.Format("{0:0.00}", decimalValue * 100);
You can use .Format() as an alternative to .ToString("0.00").
Since decimal? does not have a ToString(string format) overload, the easiest way is to use String.Format instead which will provide consistent results with the null case for decimalValue as well (resulting in an empty string) when compared to your original code:
string value = String.Format("{0:#.##}", decimalValue * 100);
But there are some other considerations for other numbers that you weren't clear on.
If you have a number that does not produce a value greater than 0, does it show a leading zero? That is, for 0.001211, does it display as 0.12 or .12? If you want the leading zero, use this instead (notice the change from #.## to 0.##):
string value = String.Format("{0:0.##}", decimalValue * 100);
If you have more than 2 significant decimal places, do you want those displayed? So if you had .12113405 would it display as 12.113405? If so use:
string value = String.Format("{0:#.############}", decimalValue * 100);
(honestly, I think there must be a better formatting string than that, especially as it only supports 12 decimal places)
And of course if you want both leading zeros and multiple decimal places, just combine the two above:
string value = String.Format("{0:0.############}", decimalValue * 100);

Categories