How to convert a string to decimal with 2 decimal places? - c#

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;
}

Related

Extra zeroes when parsing string to decimal

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);

How change the standard form format of double.ToString();

the following code:
double number = 85047564288067.5
string numberString = number.toString("G3");
Console.WriteLine(numberString);
will print: 8.5E+13
which obviously is correct but is there a way for the toString() function to return numbers that are in standard form in the format: 8.5x10^13?
Just replace E with x10^:
string numberString = number.ToString("G3", CultureInfo.InvariantCulture)
.Replace("E", "x10^").Replace("+", "");
If it's just for display purposes, then this should do the job.
double number = 85047564288067.5;
string numberString = number.ToString("G3").Replace("E+","x10^");
Console.WriteLine(numberString);
You can use it more effectively as follows
Extension Method
public static class DoubleExtension
{
public static string ToString10Th(this double p)
{
return p.ToString("0.#E+0", CultureInfo.InvariantCulture).Replace("E-", "x10^-").Replace("E+", "x10^");
}
}
Usage
double number = 85047564288067.5;
Console.WriteLine(number.ToString10Th());
Try with exponential notation.
Maybe something like this:
double number = 85047564288067.5
string numberString = string.Format("{0:0.#E+00}", number);
Console.WriteLine(numberString);

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 Convert string("1.0000") to int

The string format data with mostly 4 decimal places needs to be converted into int.
I have tried this one but does not work and even directly using this Convert.ToInt16() but still did not worked:
Int32 result;
bool status = Int32.TryParse(v, out result);
Is there other ways to convert this?
Thanks.
You can convert it to Double first, and then convert to Int32
String s = "1.0000";
Double temp;
Boolean isOk = Double.TryParse(s, out temp);
Int32 value = isOk ? (Int32) temp : 0;
You can use the following:
string data = "1.0000";
int number
if(data.Contains('.'))
number = int.Parse(data.Substring(0, data.IndexOf('.'))); //Contains decimal separator
else
number = int.Parse(data); //Contains only numbers, no decimal separator.
Because 1.0000 has decimal places, first strip those from the string, and then parse the string to int.
You have to parse it as decimal and then cast to int.
decimal resultTmp;
bool status = Decimal.TryParse("1.000".Replace(".",","), out resultTmp);
int result = (int)resultTmp;
Also change '.' to ','

C# how to convert a double to string with exponential notation

I'm trying to convert double to string in format of exponential notation.
for example:
double l_dNum = 3.333;
string l_strNum = l_dNum.ToString();
Console.WriteLine(l_strNum);
//Wanted results: 3.33e+00
Thanks!
From MSDN examples
string l_strNum = l_dNum.ToString("E");
If you want up to 2 decimals only
string l_strNum = l_dNum.ToString("E2");

Categories