Convert text to integer to compare in C# - c#

The C# program receives a string labeled:
1.2345 V
I need to compare this value using < or > in a 'if' statement.
How do I convert the string above to a integer?
I tried to use:
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
But it throws the error System.FormatException: incorrect format.

In case you insist on integer (dot in 1.2345 shoud be ignored and final result is 12345):
// Any digits (including, say, Persian ones) are OK
int anInteger = (textBox1.Text
.Where(c => char.IsDigit(c))
.Aggregate(0, (s, a) => s * 10 + (int)char.GetNumericValue(a));
Or
// Only '0'..'9' digits supported
int anInteger = (textBox1.Text
.Where(c => c >= '0' && c <= '9')
.Aggregate(0, (s, a) => s * 10 + a - '0');

You have to remove the V at the end and use decimal.Parse/ TryParse:
decimal d;
bool validFormat = decimal.TryParse(textBox1.Text.TrimEnd('V', ' '), out d);
In my country which uses , as decimal and . as group separator this yields 12345.
If you instead want to ignore anything that is not a digit in a string:
int number = int.Parse(new string(textBox1.Text.Where(char.IsDigit).ToArray()));

Please also notice that depends on your current culture settings you can get different results.
Following code was run with de-DE culture settings
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 123
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 1,23
Following code was run with en-US culture settings
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 1.23
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 123
Please use LINQPad to run that code.

you can try -
decimal dec=2;
string str = "3.23456";
dec = Convert.ToDecimal(str.ToString());
int a = Convert.ToInt32(dec);

Related

How to format floating point value with fix number of digits?

Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?
Say I wish 6 digits, I want to have these results:
0.00123456789 gives "0.00123"
1.23456789 gives "1.23457"
123.456789 gives "123.457"
0.0000000123456789 gives "0.00000"
12345678.9 gives "12345679" (on overflow I want to see all digits left of decimalpoint)
4.2 gives "4.20000"
I'm experimenting with double.ToString, but cannot find any suitable format string.
Already tried "G6" (gives sometimes exponential format), "F6" (comes close, but 0.123456789 gives "0.123457" which are 7 digits).
I think some of your examples are wrong.
But I still think that I understand what you want to achieve.
I made an extension method.
public static class StringExtensionMethods
{
public static string ToString(this double d, int numberOfDigits)
{
var result = "";
// Split the number.
// Delimiter can vary depending on locale, should consider this and not use "."
string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
if(split[0].Count() >= numberOfDigits)
{
result = split[0].Substring(0, numberOfDigits);
}
else
{
result = split[0];
result += ".";
result += split[1];
// Add padding.
while(result.Count() < numberOfDigits +1)
result += "0";
result = result.Substring(0, numberOfDigits + 1);
}
return result;
}
}
I ran it with your examples:
double d0 = 0.00123456789;
double d1 = 1.23456789;
double d2 = 123.456789;
double d3 = 0.0000000123456789;
double d4 = 12345678.9;
double d5 = 4.2;
Console.WriteLine(d0.ToString(6));
Console.WriteLine(d1.ToString(6));
Console.WriteLine(d2.ToString(6));
Console.WriteLine(d3.ToString(6));
Console.WriteLine(d4.ToString(6));
Console.WriteLine(d5.ToString(6));
This is the output:
0.00123
1.23456
123.456
1.23456
123456
4.20000
I don't think this is the best way to solve it, but I like extension methods.
DoubleConverter class: http://1drv.ms/1yEbvL4
If your goal is to avoid "jumping" of the decimal point:
Use g formating, this does the most sensible thing to do
See where the decimal point is in your resulting string
pad with spaces at the beginning to align the column at the decimal point
As I understand, there is no predefined format that does what I need. So for everyone who is interested, here is the function I ended up with:
public string FormatValue(double d, int noOfDigits)
{
double abs = Math.Abs(d);
int left = abs < 1 ? 1 : (int)(Math.Log10(abs) + 1);
int usedDigits = 0;
StringBuilder sb = new StringBuilder();
for(; usedDigits < left; usedDigits++)
{
sb.Append("0");
}
if(usedDigits < noOfDigits)
{
sb.Append(".");
for(; usedDigits < noOfDigits; usedDigits++)
{
sb.Append("0");
}
}
return d.ToString(sb.ToString());
}

String/Int to double with precision defined onruntime

I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}

How to display number in money format

How to display Number with comma in following format in C#.
Ex: 12345678
I want to display this number as 1,23,45,678
Can any one give answer for this.
Thanks.
As I understand, this is an Indian style of formatting the currency.
Console.WriteLine(intValue.ToString("N1", CultureInfo.CreateSpecificCulture("hi-IN")));
where intValue is the number you want to format.
For the same input in your question, you should get exactly "1,23,45,678".
Try this
int number = 12345678 ;
Convert.ToDecimal(number).ToString("#,##0");
string.Format("{0:C}", 12345678)
You may try this:-
Double number = 12345678;
String output = number.ToString("C2");
Check out the Currency Formatter.
The "C" (or currency) format specifier converts a number to a string
that represents a currency amount. The precision specifier indicates
the desired number of decimal places in the result string. If the
precision specifier is omitted, the default precision is defined by
the NumberFormatInfo.CurrencyDecimalDigits property.
You can use Custom Format The Currency Format Specifier C or c using ToString()
From MSDN: Custom Format c or C
Result: A currency value.
Supported by: All numeric types.
Precision specifier: Number of decimal digits.
Default precision specifier: Defined by System.Globalization.NumberFormatInfo.
Try This:
int myVal= 12345678;
string finalVal= myVal.ToString("C");
Console.WriteLine(finalVal);
Try This: if you dont want precision.
int myVal= 12345678;
string finalVal= myVal.ToString("C0");
Console.WriteLine(finalVal);
you can use cultureinfo to show currency with your number
decimal dec = 123.00M;
string uk = dec.ToString("C", new CultureInfo("en-GB"); // uk holds "£123.00"
string us = dec.ToString("C", new CultureInfo("en-US"); // us holds "$123.00"
Well, a very dirty solution, but could not figure if there is a format for this.
So I take last 3, then by packs of two :
int number = 212345678;
string semiRes = number.ToString();
var lastThree = semiRes.Substring(semiRes.Length - 3, 3);
List<string> resulatArray = new List<string>();
resulatArray.Add(lastThree);
semiRes = semiRes.Substring(0, semiRes.Length - 3);
for (int i = 2; i <= semiRes.Length + 2; i = i + 2)
{
var start = semiRes.Length - i;
var len = 2;
if (start < 0)
{
len = 2 + start;
start = 0;
}
var nextTwo = semiRes.Substring(start, len);
resulatArray.Insert(0, nextTwo);
}
var result = string.Join(",", resulatArray);
if (result.StartsWith(","))
{
result = result.Substring(1);
}
int number = 123456789;
string Result = number.ToString("#,##0");
Try this.
Hope it helps
using System.Globalization;
NumberFormatInfo info = new NumberFormatInfo();
info.NumberGroupSizes = new int[] { 3, 2 };
int number = 12345678;
string Result = number.ToString("#,#", info);
here you Go...

Converting number to comma separated values

I need to convert numbers into a comma separated format to display in C#.
For Example:
1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000
How to achieve this in C#?
I tried the below code:
int number = 1000;
number.ToString("#,##0");
But it is not working for lakhs.
I guess you can do this by creating a custom number format info for your needs
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";
Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000
if specifically only for numbers then you could also do
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
Console.WriteLine(15000000.ToString("N0", nfo));
Here's a similar thread to yours add commas in thousands place for a number
and here's the solution that worked perfectly for me
String.Format("{0:n}", 1234);
String.Format("{0:n0}", 9876); // no decimals
If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.
public static string CommaInt(int Number,int Comma)
{
string IntegerNumber = Number.ToString();
string output="";
int q = IntegerNumber.Length % Comma;
int x = q==0?Comma:q;
int i = -1;
foreach (char y in IntegerNumber)
{
i++;
if (i == x) output += "," + y;
else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
else output += y;
}
return output;
}
Have you tried:
ToString("#,##0.00")
Quick and dirty way:
Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);
An easy solution would be to pass a format into the ToString() method:
string format = "$#,##0.00;-$#,##0.00;Zero";
decimal positiveMoney = 24508975.94m;
decimal negativeMoney = -34.78m;
decimal zeroMoney = 0m;
positiveMoney.ToString(format); //will return $24,508,975.94
negativeMoney.ToString(format); //will return -$34.78
zeroMoney.ToString(format); //will return Zero
Hope this helps,

Printing numbers after decimal point

How can i print the numbers of a float/double variable after the decimal point?
For example for 435.5644 it will output 5644.
try with
fraction = value - (long) value;
or :
fraction = value - Math.Floor(value);
You can try the following:
double d = 435.5644;
int n = (int)d;
var v = d - n;
string s = string.Format("{0:#.0000}", v);
var result = s.Substring(1);
result: 5644
EDIT: reference to another question (http://stackoverflow.com/questions/4512306/get-decimal-part-of-a-number-in-javascript)
You can do the following:
double d = 435.5644;
float f = 435.5644f;
Console.WriteLine(Math.Round(d % 1, 4) * 10000);
Console.WriteLine(Math.Round(f % 1, 4) * 10000);
That will give you the integer part you looking for.
Best is to do it as Aghilas Yakoub answered, however, here below another option using string handling. Assuming all amounts will have decimals and that decimal separator is a dot (.) you just need to get the index 1.
double d = 435.5644;
Console.WriteLine(d.ToString().Split('.')[1]);
float f = 435.5644f;
Console.WriteLine(f.ToString().Split('.')[1]);
Otherwise you may get a Unhandled Exception: System.IndexOutOfRangeException.

Categories