How would I convert the following code to C#
DecimalFormat form
String pattern = "";
for (int i = 0; i < nPlaces - nDec - 2; i++) {
pattern += "#";
}
pattern += "0.";
for (int i = nPlaces - nDec; i < nPlaces; i++) {
pattern += "0";
}
form = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = form.getDecimalFormatSymbols();
symbols.setDecimalSeparator('.');
form.setDecimalFormatSymbols(symbols);
form.setMaximumIntegerDigits(nPlaces - nDec - 1);
form.applyPattern(pattern);
EDIT The particular problem is that I do not wish the decimal separator to change with Locale (e.g. some Locales would use ',').
For decimal separator you can set it in a NumberFormatInfo instance and use it with ToString:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
//** test **
NumberFormatInfo nfi = new NumberFormatInfo();
decimal d = 125501.0235648m;
nfi.NumberDecimalSeparator = "?";
s = d.ToString(nfi); //--> 125501?0235648
to have the result of your java version, use the ToString() function version with Custom Numeric Format Strings (i.e.: what you called pattern):
s = d.ToString("# ### ##0.0000", nfi);// 1245124587.23 --> 1245 124 587?2300
// 24587.235215 --> 24 587?2352
System.Globalization.NumberFormatInfo
In C#, decimal numbers are stored in the decimal type, with an internal representation that allows you to perform decimal math without rounding errors.
Once you have the number, you can format it using Decimal.ToString() for output purposes. This formatting is locale-specific; it respects your current culture setting.
Related
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);
I have to read and write an excel file.
The problem is that when a PC is the decimal separator, (comma) also in the excel file numbers with the comma will be saved.
I would like to save the values for all modes with the point instead of a comma.
Here is a piece of code:
var wb = openWorkBook(filename);
var ws = wb.Worksheet("CNF");
IXLRow row = ws.Row(device.Ordinal - 1 + FirstRow);
for (int j = 0; j < MAXCOLS; ++j)
{
IXLCell cell = row.Cell(j + FirstCol);
cell.Value = Convert.ChangeType(device[j], m_column_type[j]);
}
Convert.ChangeType(object, Type) uses the thread's current culture for conversion. It sounds like you want the invariant culture, so you should use Convert.ChangeType(object, Type, IFormatProvider):
cell.Value = Convert.ChangeType(device[j], m_column_type[j],
CultureInfo.InvariantCulture);
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());
}
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...
I would like to parse string value like this :
.02234
-.23455
-1.23345
2.
.3
but i get an FormatException
for (int i = 1; i < 7; i++)
{
var item = Double.Parse(reader.ReadLine(44).Substring(8 * i, 8));
richTextBox1.Text += item.ToString() + "\n";
}
the problem that i should convert this numbers like "0.2" or "-.0541" to double or any value type to work with it !!!
Since you've made a comment that , is the decimal separator in your locale, there is a better option than doing a string-replace of . to ,; tell the Double.Parse() method to use a different number format.
See the MSDN doc for Parse(String s). Especially, note the following:
The s parameter is interpreted using
the formatting information in a
NumberFormatInfo object that is
initialized for the current thread
culture. For more information, see
CurrentInfo. To parse a string using
the formatting information of some
other culture, call the
Double.Parse(String, IFormatProvider)
or Double.Parse(String, NumberStyles,
IFormatProvider) method.
Assuming your current thread culture is using a number format that considers , to be the decimal separator (French/France fr-FR, for example), you must pass an IFormatProvider to the Parse() method that defines . as the decimal separator. Conveniently, the "no culture in particular" culture, CultureInfo.InvariantCulture, does just this.
So this code should parse successfully:
for (int i = 1; i < 7; i++)
{
// Assume the substring of ReadLine() contains "-.23455", for example
var item = Double.Parse(reader.ReadLine(44).Substring(8 * i, 8), CultureInfo.InvariantCulture);
richTextBox1.Text += item.ToString() + "\n";
}
You're passing a string that isn't a double, something like 1.a or 1. .3 (1 string representing 2 numbers)
You can use Double.TryParse() and it will not throw an exception but return true/false if it was successful or not. It might make the flow easer.
reader.ReadLine(44).Substring(8 * i, 8).ToString()
You won't need the .ToString(). Verify that this actually returns the value you're looking for.
The format exception is throw because the value it's trying to parse is not valid!
My first guess is that the argument you're passing is not in fact a double.
Might try to split up your calls, and toss in a breakpoint to see what's actually going on.
for (int i = 1; i < 7; i++)
{
string textNum = reader.ReadLine(44).Substring(8 * i, 8);
// add a breakpoint on the next line, then look at textNum. I bet it's not what you hoped.
double item = double.Parse(textNum);
richTextBox1.Text += string.Format("{0}\n", item);
}
Use Double.TryParse() and test to see if the value was successfully parsed into your local variable like this:
for (int i = 1; i < 7; i++)
{
double value = 0;
string input = reader.ReadLine(44).Substring(8 * i, 8);
if (Double.TryParse(input, out value))
{
richTextBox1.Text += value.ToString() + "\n";
}
else
{
richTextBox1.Text = "Invalid double entered.";
}
}
i just find a solution to the problem ( replace to dot with comma ) :
public Double[] GridValues(int fromline)
{
Double[] values = new Double[7];
for (int i = 1; i < 7; i++)
{
string input = ReadLine(fromline).Substring(8 * i, 8).Replace(".", ",");
values[i-1] = double.Parse(input);
}
return values;
}