Convert string value into decimal with proper decimal points - c#

i have value stored in string format & i want to convert into decimal.
ex:
i have 11.10 stored in string format when i try to convert into decimal it give me 11.1 instead of 11.10 .
I tried it by following way
string getnumber="11.10";
decimal decinum=Convert.ToDecimal(getnumber);
i tried this also
decinum.ToString ("#.##");
but it returns string and i want this in decimal.
what could be the solution for this?

As already commented 11.1 is the same value as 11.10
decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);
Will output true
The # formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0 in 4.05 wouldn't be suppressed). Try
decinum.ToString("0.00");
And you will see the string value of 11.10
Ideally you actually want to use something like
string input="11.10";
decimal result;
if (decimal.TryParse(input,out result)) {
Console.WriteLine(result == 11.10);
} else {
// The string wasn't a decimal so do something like throw an error.
}
At the end of the above code, result will be the decimal you want and "true" will be output to the console.

this will work perfectly
string getnumber = "11.10";
decimal decinum = Math.Round(Convert.ToDecimal(getnumber), 2);

A decimal datatype stores a value. The value of 11.1 is identical to that of 11.10 - mathemtically, they're the exact same number, so it's behaving properly.
What you seem to want is to display the number as 11.10, but that's up to the code that displays it - I don't know if you're writing to log file, displaying on a web-page or any other format - but that is independent of the internal representation of the decimal datatype.

there is no solution, This is expected behaviour.
11.10 in string = 11.1 in number
you cant store zeros on the decimal part, otherwise 11.10 would be different than 11.100, which is true if you are talking about strings but not if you are talking about numbers.
I think your problem is on a presentation level only. Why dont you explain better what you want to do.

11.10 expressed as a decimal is 11.1, just like it is 11.100000000000000000000000000000000000.
For mathematical processes, don't worry about how it displays itself. If you are displaying the value then converting it into a string is no biggie either. Remember that
decinum.ToString ("#.##");
is returning a string (from the 'ToString' function) and not converting the 'decinum' to a string.

string getnumber = "11.10";
double decinum = double.Parse(getnumber);

Related

C# String format: escape a dot

I have a line of code, something like:
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
Output is: 2.25 for example. Is it possible to escape a dot from the output string view with String.Format function ?
For. ex. 225,
To make my question more clear, I need the same effect like:
Math.Floor(_hp * 100).ToString();
But need to do it by String.Format template.. Thanks.
Simply you can do it this way
double value = 1.25;
var stringValue = string.Format("{0:0}", value * 100, CultureInfo.InvariantCulture); //125
EDIT:
More general solution would be to Replace the dot with empty string as stated in the comments.
double value = 1.25;
var stringValue = value.ToString(CultureInfo.InvariantCulture).Replace(".",string.Empty);
EDIT2: Also there is another general idea that do not use Replace function (but also it does not use the String.Format)
var stringValue = string.Join("", value.ToString().Where(char.IsDigit));
Also another similar idea:
var stringValue = new string(value.ToString().Where(char.IsDigit).ToArray());
First of all, please read my comment to the question. As i mentioned there, string format for numeric values depends on regional settings. So, below line
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
will return: 2,25 (as to the polish numeric standard)
In my opinion you need something like this:
mbar.HealthLabel.text = String.Format("{0:D}", Math.Floor(_hp*100));
For furhter details, please see:
Standard Numeric Format Strings
Custom Numeric Format Strings
Up to Microsoft.NET Framework 4.7 there is no way to solve this when we are only allowed to modify the format string ("template"). All solutions require to either:
Post-process the resulting string. Here, the closest for the special case with two decimals may be the % format
Compute the numeric argument first to make it integer
Write and apply a custom IFormatProvider implementation
If you want to eliminate the decimal separtor ("escape the dot", as you've put it), try replacing the decimal separator with empty string:
string result = String
.Format("{0:0.0}", _hp)
.Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "");

Convert Number without leading zero for using in C#

I have a Oracle-view which gives me those data:
DATUM STUNDE LAUFZEIT
-------------- ---------- -----------
30.10.14 00:00 11 ,433333333
The column LAUFZEIT is declared as NUMBER. Which format to I need to convert the column to get 0,433333333 or rounded to 0,4?
I already tried some types like Convert.ToSingle(reader.GetValue(2)) but always get a error like
System.OverflowException: Arithmetic operation resulted in an overflow
Thanks!
You have to mention a currect Culture:
Object source = ",433333333";
// This will fail with exception - Neutral Culture uses decimal point, not comma
//Single single = Convert.ToSingle(source, CultureInfo.InvariantCulture);
// OK: Russian culture (ru-RU) uses decimal comma, not decimal point
Single single = Convert.ToSingle(source, new CultureInfo("ru-RU"));
To represent the value in desired form, use formatting, e.g. for 0,4:
// F1 - one floating point
// "ru-RU" for decimal comma
String result = single.ToString("F1", new CultureInfo("ru-RU"));
Edit: having seen on the Exception stack trace, i.e.
Arithmetic operation resulted in an overflow. at Oracle.DataAccess.Types.DecimalConv.GetDecimal(IntPtr numCtx)
one can conclude that the problem is in the
`Oracle.DataAccess.Types.DecimalConv.GetDecimal`
the origin of the error may be in the fact that Oracle Number(36) or the the like is bigger that .Net Decimal. Since you can't change Oracle.DataAccess library you can convert to String just in the query:
select ...
cast(LAUFZEIT as VarChar2(40)),
...
you can always add a leading zero yourself before parsing. Adding a zero to the start of a number will NEVER change it.
Convert.ToSingle('0' + reader.GetString(2).Replace(',','.')) should do it.
I advice to use reader.GetString() before parsing.
Also it would be better to do:
Single a ;
if(Single.TryParse('0' + reader.GetString(2).Replace(',','.')), out a))
{
//Success code here
}
else
{
//Code to execute if string was not parsable here
}
In this way you won't get an exception

C# - Format float WITHOUT tail zeros

Is that possible in C# to format
4.52 float number to 4.52 string
and
4.520 float number to 4.52 string, i.e. omitting tail zeros?
EDIT: I think I've not accented the real problem.
I need ONE pattern that conforms BOTH of the above examples!
Assuming you want to omit any trailing 0's from your value, this should give you what you want:
ToString("0.####")
Otherwise you could do:
ToString("0.00##")
See this website for examples.
i.e
String.Format("{0:0.00}", 4.520); // "4.52"
Actually, you don't need a pattern. .NET always omits the tail zeros of float numbers, unless specified to do not.
So Console.WriteLine(4.520) would output 4.52, as would Console.WriteLine(4.52) or Console.WriteLine(4.520000000000), as Console.WriteLine(4.5) would output 4.5.
In the example above, the System.Console.WriteLine method will internally call ToString() (with no patterns) on your float number.
Also, if you're looking for something more specific, you can take a look at
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.71).aspx
for some more number format strings.
All of these result in "4.52":
string formatted = 4.52.ToString();
string formatted = 4.520.ToString();
Because that was too easy I wonder if maybe your float is really a string:
string formatted = "4.52".Trim('0');
string formatted = "4.520".Trim('0');

Convert ComboBox to Decimal, C#

I am trying to create a combobox that contains text and when each text is chosen the text will equal a decimal and later be used in a math code. I am using C# inside Visual Studio.
I am a beginner and any help will be greatly appreciated.
Thanks,
Royal
That should be reasonably simple. You can use Decimal.Parse() to convert the selected string value to a decimal:
decimal val = Decimal.Parse(someComboBox.SelectedItem.ToString());
If you know that the string is definately a Decimal you can use Justin's answer, if you are unsure if it is a Decimal you could also try:
decimal ParseDecimal(string str){
decimal number;
if(Decimal.TryParse(str, out number)
{
return number;
}
return decimal.MinValue (or any other value that you know to check against)
}
Where the string you pass into the method is the combo box string.
Are you looking to convert the input string to decimal? This may help. http://msdn.microsoft.com/en-us/library/59095yyw.aspx and also Decimal.TryParse http://msdn.microsoft.com/en-us/library/9zbda557.aspx
or if you are sure you can use Convert method:
decimal val =
Convert.ToDecimal(comboBox1.SelectedItem.ToString());
But becuase you said you are unsure about what string value is (or is a decimal, or a dobule, or a simple stirng, or ...) it would be better to use Darren`s version of checking, which will check if the string is a actual decimal value. If it is, it will go into the brackets (and you can do something then), if its not, then it will go over if statement (you can add an else statement to do something else.
Mitja

int.Parse() with leading zeros

How do I prevent the code below from throwing a FormatException. I'd like to be able to parse strings with a leading zero into ints. Is there a clean way to do this?
string value = "01";
int i = int.Parse(value);
Your code runs for me, without a FormatException (once you capitalize the method properly):
string value = "01";
int i = int.Parse(value);
But this does ring an old bell; a problem I had years ago, which Microsoft accepted as a bug against localization components of Windows (not .NET). To test whether you're seeing this, run this code and let us know whether you get a FormatException:
string value = "0"; // just a zero
int i = int.Parse(value);
EDIT: here's my post from Usenet, from back in 2007. See if the symptoms match yours.
For reference, here's what we found.
The affected machine had bad data for
the registry value
[HKEY_CURRENT_USER\Control Panel
\International\sPositiveSign].
Normally, this value is an empty
REG_SZ (null-terminated string). In
this case, the string was missing its
terminator. This confused the API
function GetLocaleInfoW(), causing it
to think that '0' (ASCII number zero)
was the positive sign for the current
locale (it should normally be '+').
This caused all kinds of havoc.
You can verify this for yourself with
regedit.exe: open that reg value by
right-clicking on the value and
selecting 'Modify Binary Data'. You
should see two dots on the right
(representing the null terminator).
If you see no dots, you're affected.
Fix it by adding a terminator (four
zeros).
You can also check the value of
CultureInfo.CurrentCulture.NumberFormat.PositiveSign;
it should be '+'.
It's a bug in the Windows localization
API, not the class libs. The reg
value needs to be checked for a
terminator. They're looking at it.
...and here's a report on Microsoft Connect about the issue:
Try
int i = Int32.Parse(value, NumberStyles.Any);
int i = int.parse(value.TrimStart('0'));
TryParse will allow you to confirm the result of the parse without throwing an exception. To quote MSDN
Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
To use their example
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
You don't have to do anything at all. Adding leading zeroes does not cause a FormatException.
To be 100% sure I tried your code, and after correcting parse to Parse it runs just fine and doesn't throw any exception.
Obviously you are not showing actual code that you are using, so it's impossible to say where the problem is, but it's definitely not a problem for the Parse method to handle leading zeroes.
Try
int i = Convert.ToInt32(value);
Edit: Hmm. As pointed out, it's just wrapping Int32.Parse. Not sure why you're getting the FormatException, regardless.
I have the following codes that may be helpful:
int i = int.Parse(value.Trim().Length > 1 ?
value.TrimStart(new char[] {'0'}) : value.Trim());
This will trim off all extra leading 0s and avoid the case of only one 0.
For a decimal number:
Convert.ToInt32("01", 10);
// 1
For a 16 bit numbers, where leading zeros are common:
Convert.ToInt32("00000000ff", 16);
// 255

Categories