decimal value = 10;
int decimalPosition= 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);
if decimalPosition =3;
I need to display formatted value like : 10.000.
if decimalPosition =5;
I need to display formatted value like : 10.00000.
Note: I must use Round function.
decimal value has no format assigned - it is just a numeric value. You can specify the format it's being printed out with, but you have to do it while printing or when the string is being created:
decimal value = 10;
int decimalPosition = 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);
string format = string.Format("{{0:0.{0}}}", string.Concat(Enumerable.Repeat("0", decimalPosition).ToArray()));
string formattedString = string.Format(format, formatted);
Console.WriteLine(formattedString);
Prints 10.000 into console.
Another way of specifying format like that:
var format = string.Format("{{0:f{0}}}", decimalPosition);
You can try something like this:-
decimal.Round(yourValue, decimalPosition, MidpointRounding.AwayFromZero);
u can try it:--
decimal value = 10;
int decimalPosition = 3; //this decimalPosition will be dynamically change.
string position = "";
for (int i = 0; i < decimalPosition; i++)
{
position += "0";
}
string newValue = value.ToString() + "." + position;
decimal formatted = Convert.ToDecimal(newValue);
Use FORMATASNUMBER(Value, decimalPosition) instead of math.round
Sorry, I forgot it was c# not VB
But you can read about it here on MSDN
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(v=VS.80).aspx
The command is String.FormatNumber(blah blah blah)
and the ACTUAL declaration is...
public static string FormatNumber (
Object Expression,
[OptionalAttribute] int NumDigitsAfterDecimal,
[OptionalAttribute] TriState IncludeLeadingDigit,
[OptionalAttribute] TriState UseParensForNegativeNumbers,
[OptionalAttribute] TriState GroupDigits
)
Related
Why does the below code throw a System.FormatException -
Input string was not in a correct format
decimal sum = 0;
string valString = "3.5";
sum += Convert.ToInt32(valString);
Well, 3.5 is not a correct integer value (please, notice fraction part - .5), it's decimal in the context:
decimal sum = 0;
string valString = "3.5";
sum += Convert.ToDecimal(valString);
Please try this:
sum += System.Convert.ToDecimal(valString);
I have the number 123.1234567890129.
I want the result to be 123.123456789012 without the last digit being rounded.
I've tried:
("123.1234567890129").ToString("G15") //123.123456789013
One way that you could do this is to round to 16 like this
("123.1234567890129").ToString("G16").Substring(0, 16);
Since you said double.
Since doubles can have ANY number of digits you must round in some way. (you either round down, as inferred or you round up as in practice for this case)
Since you imply you only want to see the number of precise digits, you must find out how many digits are on each side of the decimal point (0 to 15 on either side)
An extenstion to round down
public static class DoubleExtensions
{
public static double RoundDown(this double value, int numDigits)
{
double factoral = Math.Pow(10, numDigits);
return Math.Truncate(value * factoral) / factoral;
}
}
test case
const int totalDigits = 15;
// why start with a string??
string somestring = "123.1234567890129";
const int totalDigits = 15;
// since the title says 'convert a double to a string' lets make it a double eh?
double d = double.Parse(somestring);
int value = (int)d;
double digitsRight = d - value;
int numLeft = (d - digitsRight).ToString().Count();
int numRight = totalDigits - numLeft;
double truncated = d.RoundDown(numRight);
string s = truncated.ToString("g15");
You can create custom FormatProvider and then create your implementation.
class Program
{
static void Main(string[] args)
{
double number = 123.1234567890129;
var result = string.Format(new CustomFormatProvider(15), "{0}", number);
}
}
public class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
private readonly int _numberOfDigits;
public CustomFormatProvider(int numberOfDigits)
{
_numberOfDigits = numberOfDigits;
}
public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? this : null;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!Equals(formatProvider))
return null;
if (!(arg is double))
{
return null;
}
var input = ((double)arg).ToString("R");
return input.Length > _numberOfDigits + 1 ? input.Substring(0, _numberOfDigits + 1) : input; // +1 because of dot
}
Unfortunately you cannot do in this way:
var result = number.ToString(new CustomFormatProvider(15));
because of value types limitation.. Double supports only CultureInfo and NumberFormatInfo formatters. If you pass different formatter it will return default instance: NumberFormatInfo.CurrentInfo'. You can make small workaround by usingstring.Format` method.
New to the community. First answer here. :)
I think you are looking for something like this. Works with or without decimal. This will cut the digits after the 15th digit only irrespective of length of the number. You can get the user to decide the accuracy by getting the precision value as a user input and performing that condition check accordingly. I used 15 because you mentioned it. Let me know if it works for you. Cheers!
string newstr;
int strlength,substrval;
double number;
string strnum = "123.1234567890129";
strlength = strnum.Length;
if(strlength>15)
{
strlength = 15;
}
substrval = strlength;
foreach(char x in strnum)
{
if(x=='.')
{
substrval++;
}
}
newstr = strnum.Substring(0, substrval);
number=Convert.ToDouble(newstr);
Alife Goodacre, code is printing "123.12345678901" insted "123.123456789012"
there should be Substring(0, 16) insted of Substring(0, 15)
Convert.ToDouble("123.1234567890129").ToString("G16").Substring(0, 16)
OutPut Screen with Code.
There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();
You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.
If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0
First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.
the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....
Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.
i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.
int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...
Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:
int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
int result = parsed + 2;
string add = result.ToString();
// Use add here
}
else
{
// Indicate failure to the user; prompt them to enter an integer.
}
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.
const int addend = 2;
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
doubleArray[index] =
Char.GetNumericValue(myTextBoxText.ToCharArray()[index])
* (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add =
(doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
string add=(int.Parse(mytextbox.Text) + 2).ToString()
if you want to make sure the conversion doesn't throw any exception
int textValue = 0;
int.TryParse(TextBox.text, out textValue);
String add = (textValue + 2).ToString();
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
String add = (intValue + 2).ToString();
}
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
private int MyTextBoxInt
{
get
{
return Int32.Parse(mytextbox.Text);
}
}
And then you can use the property like this:
int result = this.MyTextBoxInt + 2;
All began with these simple lines of code:
string s = "16.9";
double d = Convert.ToDouble(s);
d*=100;
The result should be 1690.0, but it's not. d is equal to 1689.9999999999998.
All I want to do is to round a double to value with 2 digit after decimal separator.
Here is my function.
private double RoundFloat(double Value)
{
float sign = (Value < 0) ? -0.01f : 0.01f;
if (Math.Abs(Value) < 0.00001) Value = 0;
string SVal = Value.ToString();
string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
int i = SVal.IndexOf(DecimalSeparator);
if (i > 0)
{
int SRnd;
try
{
// вземи втората цифра след десетичния разделител
SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1));
}
catch
{
SRnd = 0;
}
if (SVal.Length > i + 3)
SVal = SVal.Substring(0, i + 3);
//SVal += "00001";
try
{
double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal);
//result = Math.Round(result, 2);
return result;
}
catch
{
return 0;
}
}
else
{
return Value;
}
But again the same problem, converting from string to double is not working as I want.
A workaround to this problem is to concatenate "00001" to the string and then use the Math.Round function (commented in the example above).
This double value multiplied to 100 (as integer) is send to a device (cash register) and this values must be correct.
I am using VS2005 + .NET CF 2.0
Is there another more "elegant" solution, I am not happy with this one.
Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:
string s = "16.9";
decimal m = Decimal.Parse(s) * 100;
double d = (double)m;
You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.
Math.Round(number, 1)
Edit I got the wrong question - the rounding problems are inherent to a floating point type (float, double). You should use decimal for this.
The best solution for not going be crazy is:
string s = "16.9";
For ,/.
double d = Convert.ToDouble(s.Replace(',','.'),System.Globalization.CultureInfo.InvariantCulture);
For rounding:
Convert.ToDouble((d).ToString("F2"));