Extra zeroes when parsing string to decimal - c#

I want to parse a string entered in a WinForms text box as a decimal. These values are then stored in a property in an object. They should parsed to two decimal places, exactly like the following examples:
string amount1 = 2; // should be parsed as 2.00
string amount2 = 2.00; // should be parsed as 2.00
string amount3 = 2.5; // should be parsed as 2.50
string amount4 = 2.50; // should be parsed as 2.50
string amount5 = 2.509; // should be parsed as 2.51
How to do this? At the moment, I am parsing as follows:
decimal decimalValue = Decimal.Parse(stringValue);

There are two operations, parsing and rounding.
decimal decimalValue = Math.Round(Decimal.Parse(stringValue), 2);

Related

How to convert a string to decimal with 2 decimal places?

I'm trying to convert a string to a decimal but have the last two values be the decimal point. Example: "001150" be converted into 11.50.
Everything I've found in my search will convert strings to a decimal but the string already has the decimal point. I might have to create a function that will make the decimal point out of the string but wanted to see if there are any other ideas first.
string input = "001150";
string convertedString = string.Format(
"{0:N2}",
double.Parse(input)/100.0
);
First check if string is a number, then divide by 100 and then format string:
public string ConvertTwoDecimals(string toConvert)
{
Double convertedValue;
var isNumber = Double.TryParse(toConvert, out convertedValue);
return isNumber ? $"{(convertedValue / 100):N2}" : $"{ 0:N2}";
}
if you need a decimal type without formatted:
public decimal ConvertToDecimal(string toConvert)
{
Decimal convertedValue;
var isNumber = Decimal.TryParse(toConvert, out convertedValue);
return isNumber ? convertedValue/100 : 0;
}

double.ToString(???) - format to drop digits BEFORE decimal point and show 2 digits AFTER decimal point?

Is it possible to dislay only the cents in an amount using only ToString(), something like 1.99.ToString("SOME FORMAT HERE")?
e.g. what if I want 1.99 to be displayed as "1 dollar(s) 99 cents"
($"{ Convert.ToInt32(amount) } dollar(s) { amount.ToString("???") } cents")?
This would work if amount is a double. If amount is string then you wouldn't need ToString() in following line. Note this is assuming a format you listed in your question:
string line = string.Concat("$", amount.ToString().Split('.')[0], " dollar(s) ", amount.ToString().Split('.')[1].Substring(0,2), " cents");
I don't think you will be able to do this with only the ToString method, so here's another way.
You can first get the decimal part by doing this:
var decimalPart = yourDouble - (int)yourDouble;
Then, you can times the decimal part by 100 and convert the result to an int.
var twoDigits = (int)(decimalPart * 100);
To convert this to a two digit string, you just pad 0s to the left:
var result = twoDigits.ToString().PadLeft(2, '0');
I can not do this using only ToString(), but this is almost what you want :)
double d = 15.12;
var str = d.ToString("0 dollar(s) .00 cents").Replace(".", string.Empty);
Anyway, I suggest you to create an extension method to do this:
public static class Extensions
{
public static string ToFormattedString(this double number)
{
var integerPart = Convert.ToInt32(number);
var decimalPart = Convert.ToInt32((number - integerPart) * 100);
return String.Format("{0} dollar(s) {1} cents", integerPart, decimalPart);
}
}
usage:
Console.WriteLine(d.ToFormattedString());

How to format a value with a single decimal place using C#

I need to convert some value into decimal. i have done with the below:
Double calculateinputPower="somegivenvalue";
String valuePower="somevalue";
Double calculatePower = Double.Parse(valuePower);
calculatePower = calculatePower - calculateinputPower + calculateErp * 1;
calculatePower = Double.Parse(String.Format("{0:0.0}", calculatePower));
valuePower = System.Convert.ToString(calculatePower);
ERP.Text = valuePower;
if my output value is like
ex:66.2356 -> 66.2 , 32.568 -> 32.5 , 22.35264 ->22.3
i am getting the format which i need exactly but if the output value is like
22,33,11,66,55 something like this then i want convert that value to
22->22.0
33->33.0
11->11.0
66->66.0 how can i get this in C#.
i used myVal.ToString("F"); then i am getting 0.00
if i use ToString("N2"); then i am getting 1,000.00
but i don't want money format or 0.00 format
What exactly i need is single .0 if the value is non decimal.
Just use .ToString("0.0") (Note this uses rounding so 22.26 -> 22.3)
double i = 22.23;
double j = 45;
string si = i.ToString("0.0"); //22.2
string sj = j.ToString("0.0"); //45.0
Try in this way:
valuePower = calculatePower.ToString("F1");
To learn more, follow this link
You need to look at the documentation for the format strings you're using.
You've tried F, which says as you've not specified the precision that the "Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.", which is 2 in your case.
You've tried N2, which says that the 2 is the "Precision specifier: Desired number of decimal places.".
As you only want a single decimal place, use F1 or N1, depending on your formatting requirements.
var number1 = 66.2356d;
var number2 = 66d;
var string1 = number1.ToString("N1"); // 66.2
var string2 = number2.ToString("N1"); // 66.0
See this fiddle.

Double to string with mandatory decimal point

This is probably dumb but it's giving me a hard time. I need to convert/format a double to string with a mandatory decimal point.
1 => 1.0
0.2423423 => 0.2423423
0.1 => 0.1
1234 => 1234.0
Basically, I want to output all decimals but also make sure the rounded values have the redundant .0 too. I am sure there is a simple way to achieve this.
Use double.ToString("N1"):
double d1 = 1d;
double d2 = 0.2423423d;
double d3 = 0.1d;
double d4 = 1234d;
Console.WriteLine(d1.ToString("N1"));
Console.WriteLine(d2.ToString("N1"));
Console.WriteLine(d3.ToString("N1"));
Console.WriteLine(d4.ToString("N1"));
Demo
Standard Numeric Format Strings
The Numeric ("N") Format Specifier
Update
(1.234).ToString("N1") produces 1.2 and in addition to removing additional decimal digits, it also adds a thousands separator
Well, perhaps you need to implement a custom NumberFormatInfo object which you can derive from the current CultureInfo and use in double.ToString:
var culture = CultureInfo.CurrentCulture;
var customNfi = (NumberFormatInfo)culture.NumberFormat.Clone();
customNfi.NumberDecimalDigits = 1;
customNfi.NumberGroupSeparator = "";
Console.WriteLine(d1.ToString(customNfi));
Note that you need to clone it since it's readonly by default.
Demo
There is not a built in method to append a mandatory .0 to the end of whole numbers with the .ToString() method, as the existing formats will truncate or round based on the number of decimal places you specify.
My suggestion is to just roll your own implementation with an extension method
public static String ToDecmialString(this double source)
{
if ((source % 1) == 0)
return source.ToString("f1");
else
return source.ToString();
}
And the usage:
double d1 = 1;
double d2 = 0.2423423;
double d3 = 0.1;
double d4 = 1234;
Console.WriteLine(d1.ToDecimalString());
Console.WriteLine(d2.ToDecimalString());
Console.WriteLine(d3.ToDecimalString());
Console.WriteLine(d4.ToDecimalString());
Results in this output:
1.0
0.2423423
0.1
1234.0
You could do something like this: if the number doesn't have decimal points you can format its output to enforce one decimal 0 and if it has decimal places, just use ToString();
double a1 = 1;
double a2 = 0.2423423;
string result = string.Empty;
if(a1 - Math.Floor(a1) >0.0)
result = a1.ToString();
else
result = a1.ToString("F1");
if (a2 - Math.Floor(a2) > 0.0)
result = a2.ToString();
else
result = a2.ToString("F1");
When you use "F" as formatting, the output won't contain thousands separator and the number that follows it specifies the number of decimal places.
Use ToString("0.0###########################").
It does work. I found it in duplicate of your question decimal ToString formatting which gives at least 1 digit, no upper limit
Double provides a method ToString() where you can pass an IFormatProvider-object stating how you want your double to be converted.
Additionally, it should display trailing 0 at all costs.
value = 16034.125E21;
// Display value using the invariant culture.
Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
// Display value using the en-GB culture.
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
// Display value using the de-DE culture.
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
// This example displays the following output to the console:
// -16325.62015
// -16325.62015
// -16325,62015
// 1.6034125E+25
// 1.6034125E+25
// 1,6034125E+25
Here is the documentation from MSDN.
You can cast to string and then appen ".0" if there was no decimal point given
string sValue=doubleValue.ToString();
if(!sValue.Contains('.'))
sValue+=".0";
EDIT:
As mentioned in the comments '.' may not be the decimal seperator in the current culture. Refer to this article to retrieve the actual seperator if you want make your code save for this case.

Number Formatting String

I want to make round a number to million. This is my code:
string formating = "#,#,,";
decimal abc = 1234567890m;
decimal abc2 = 0m;
string text = abc.ToString(formating); // text="1,235"
string text2 = abc2.ToString(formating); // text2=""
How to correct formatting so that text2="0"?
P/S: I use C# .Net 2.0.
You could use #,0,,.
Note that the number will be rounded, similar behaviour to your original format string:
Console.WriteLine(0m.ToString("#,0,,")); // 0
Console.WriteLine(499999m.ToString("#,0,,")); // 0
Console.WriteLine(500000m.ToString("#,0,,")); // 1
Console.WriteLine(1234567890m.ToString("#,0,,")); // 1,235
Try string formating = "#,##0"
Then you can write:
string text = (abc/1000000).ToString(formating); // text="1,235"
string text2 = (abc2/1000000).ToString(formating); // text2="0"

Categories