I have to round decimal value into 6 decimal places in C#. When i use sum of 0.046080 and 0.116220 with below code segment answer is 0.1623
DesTot = Math.Round(TotalQty + sumtot, 6);
But i want to display the answer as 0.162300
How can i do it with C#
You need to display it using ToString using the format you wish.
Something like
DesTot.ToString("0.000000")
Try format your out put display like the following
// this code always round number to 4 places and adds two zeros at the end.
double TotalQty = 0.116220;
var DesTot= Math.Round(TotalQty, 4).ToString("0.000000");
Console.Write(DesTot);
In case of your code it will be
var DesTot = Math.Round(TotalQty + sumtot, 6).ToString("0.000000");
Related
I have basically two text which I would like to plus together to get a total.
What I need this to do is :
price.Text = 50.50
addprice.Text = 140.50
price.Text + addprice.Text
to get : 191.00
I tried looking everywhere to find how to get this working, Any ideas/suggestions. Much Appreciated.
You cannot perform mathematical operations on strings directly, you need to use a numeric data type for that.
Let's do this step by step:
Convert your texts to numbers. You can use Decimal.TryParse for that. Think about what you want to happen if the text does not contain a valid number.
Add your numbers.
Convert your sum back to text. You can use Decimal.ToString for that.
Implementation is left as an exercise, but the SO crowd will surely help you if you get stuck.
Note: Since your numbers seem to be monetary values, you should use decimal rather than double or float).
var total = Convert.ToDecimal(price.Text) + Convert.ToDecimal(addPrice.Text);
Convert your strings to decimal then sum and if you want to convert back to string just: total.ToString()
As string:
string total = (decimal.Parse(price.Text) + decimal.Parse(addPrice.Text)).ToString();
or as decimal:
decimal total = decimal.Parse(price.Text) + decimal.Parse(addPrice.Text);
You need to parse those texts into a numbers (floats in this case).
float priceNumber = 0;
float addPriceNumber = 0;
if(float.TryParse(price.Text, out priceNumber) && float.TryParse(addprice.Text, out addPriceNumber )) {
//Here, the priceNumber and addPriceNumber has numbers stored as float
float result = priceNumber + addPriceNumber;
} else {
//Error parsing, wrong format of numbers
}
Docs: float.TryParse / Single.TryParse
Some knowledge about parsing: Wiki
How do I format a cell in a grid that is treated like text to be zero, one, or two digits depending on what the value is but to cut it to two digits if it has more?
If the value is 25 we display 25.
If the value is 26.3 we display 26.3.
If the value is 27.59 we display 27.59.
If the value is 28.124 we display 28.12.
If the value is 11.1111111 we display 11.11.
Does this make sense?
I'm using C#, MVC, and javascript/jquery.
If you do not want to round the value, you can do two different things:
//using String.Format()
string.Format("{0:#.##}", someValue)
//using ToString()
someValue.ToString("#.##")
Working fiddle here
If your value is not in a double/decimal then you can either manipulate the string by checking the index of the decimal point and trimming the string to 1 or 2 indexes to the right of that. However it might just be easier to parse the value into a new double then let the string formatting take it from there.
In C# you can user Math.Round function
decimal d = 28.1234;
Var a = Math.Round(d,2);
a will be 28.12
So because you said it's like a text you start with a string :
string text = "25.1234";
Then you can parse it to a double so you can round it :
double number = double.Parse(text);
Then you finish by rounding the value to the decimal you need and transforming it to a string :
text = Math.Round(number, 2).ToString();
I need to display two digits after decimal point while rounding to floor as a percentage. I wrote out this code to do so, but this looks too complex, is there another more effecient way of doing this?
double decimalPlacesFactor =Math.Pow(10, numberOfDigits+2);
percentage = Math.Floor((NumA/NumB)*decimalPlacesFactor)/decimalPlacesFactor *100;
The output should look like
99.78 %
Use the ToString() methode to convert your number to a string. Display it as a floating point with X digits by using the argument "FX". e.g. "F2" for two digits
string percentage = Math.Floor(NumA/NumB).ToString("F"+numberOfDigits);
Depends on how you want to display the percentage value, but I am guessing you'll want to show string of the percentage? What about:
string percentage = Math.Floor(NumA/NumB).ToString("0.00");
Console.WriteLine(Math.Floor(2.3).ToString("0.00")); //this will output 2.00
If you want to make the number of digits after decimal configurable you could create the masking string beforehand, with something like this:
private string CreateMaskingString(int numberOfDigits)
{
var sb = new StringBuilder("0.");
sb.Append(new string('0', numberOfDigits));
return sb.ToString();
}
And usage would look like this:
Console.WriteLine(Math.Floor(2.3).ToString(CreateMaskingString(2))); //this will output 2.00
A much more simple and elegant solution looks like this, as has been pointed out by RomCoo:
string percentage = Math.Floor(NumA/NumB).ToString("F" + numberOfDigits);
What does the "F" mean here? You can read the explanation here. But basically:
The fixed-point ("F") format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative.
I am converting data for an export.
The file shows data in cents, not dollars.
So 1234.56 needs to be printed as 123456
Is there a way to do that with string.Format?
Or is the only solution to multiply by 100?
You can use string.Replace(".", string.empty). But that isn't exactly localized. You could add in cases where you check for "," as well for international currency. But that's what I would do.
[Edit]
Also just found this:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The "N" numeric specifier allows you to change the symbol used to separate whole number and decimal parts.
<code>
decimal num = 123.456m;
NumberFormatInfo ci = CultureInfo.CurrentCulture.NumberFormat;
ci.CurrencyDecimalSeparator = " "; // You can't use string.Empty here, as it throws an exception.
string str = num.ToString("N", ci).Replace(" ", string.Empty);
</code>
Something like that should do the trick, and is localized!
That's a rendering issue. Certainly multiplying by 100 to get cents will do the job.
The United States uses the decimal point to separate dollars from cents. But not all countries do that. Your "multiply by 100" solution is only correct for currencies that use 100 fractional units to represent a single whole. (Not the case in Japan for yen.)
If it is that simple, just do String.Replace('.','');
if you know that the values will always have 2 Decimal Positions then do this it's very simple
var strVar = 1234.56;
var somevalues = string.Format("{0:######}", strVar * 100);
output = 123456
I need help converting a string to double with 7 decimals. I have a string "00000827700000" and need it converted to 82.77
Tried using String.Format() with {0:N7} without success.
It looks like you could use:
decimal x = decimal.Parse(text.Substring(0, 7) + "." +
text.Substring(7),
CultureInfo.InvariantCulture);
That would actually parse it to 82.7700000, as decimal preserves trailing zeroes (to an extent) but maybe that's good enough? It not, you could change the second argument to
text.Substring(7).TrimEnd('0')
Note that I'd strongly recommend you to at least consider using decimal instead of double. You haven't explained what this value represents, but if it's stored as decimal figures which you need to preserve, it smells more like a decimal to me.
Based on the edit, it could be simplified as
var text = "00000827700000";
var x = decimal.Parse(text, CultureInfo.InvariantCulture) / 10000000;
Console.Write(String.Format("{0:N7}", x));