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

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

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

C# padLeft, not adding pad

I am writing a method to format a phone number and also add padding to the beginning if there are less than 10 digits in the initial array. I am only failing use cases where less than 10 digits are input and my method is clearly not adding the padding. The most common mistake is using the wrong padcount parameter. I am sure I am missing something simple.
public static string CreatePhoneNumber(int[] numbers)
{
string numbas = string.Join("", numbers);
string ammendNumbas = numbas;
char pad = '0';
if ( numbas.Length < 10)
{
ammendNumbas = numbas.PadLeft(10, pad);
}
string formatString = "(###) ###-####";
var returnValue = Convert.ToInt64(ammendNumbas)
.ToString(formatString.Substring(0,ammendNumbas.Length+4))
.Trim();
return returnValue;
}
When you use Convert.ToInt64 you would be removing all padding because padding can only be applied to strings. You would need to not convert the value back to an integer after applying padding.
I think what you want is this:
public static string CreatePhoneNumber(int[] numbers)
{
Int64 numbas = Convert.ToInt64(string.Join("", numbers));
return numbas.ToString("(000) 000-0000");
}
What BlueMonk said is correct but you can do the padding with String.Format
public static string CreatePhoneNumber(int[] numbers)
{
string phoneNumberStr = string.Join("", numbers);
var phoneNumber = Convert.ToInt64(phoneNumberStr);
return String.Format("{0:(###) ###-####}", phoneNumber);
}
This is not tested but should work.
When you call Convert.ToInt64, the information of leading zeroes is lost. You can use substrings of your padded string representation to extract the digit groups:
public static string CreatePhoneNumber(int[] numbers)
{
var numberString = string.Join("", numbers);
var paddedNumbers = numberString.PadLeft(10, '0');
return $"({paddedNumbers.Substring(0, 3)}) {paddedNumbers.Substring(3, 3)}-{paddedNumbers.Substring(6)}";
}

why my parsed Double value is not right?

Im trying to parse a string to a Double.
Here is My code:
string a = "10.23";
double b = Double.Parse(a);
but b is 1023.0 and I dont know why. I would like to get 10.23 as a Double
It's because of your culture settings, you may specify culture for Parse method to get desired output:
string a = "10.23";
double b = double.Parse(a, System.Globalization.CultureInfo.InvariantCulture);
// b == 10.23
In Germany the comma (,) is used as the decimal point, whereas most English cultures and your example use the full stop (.) as the decimal point. Since Double.Parse uses the thread default culture to parse numbers, and the thread default culture is set to German, you're getting the wrong result.
You should instead specify the culture explicitly:
using System.Globalization;
string a = "10.23";
double b = Double.Parse(a, CultureInfo.InvariantCulture);
The invariant culture uses the full stop as the decimal point, so I suggest you use that instead. Or if you get the string from a source known to be written using a particular cultural convention, use that culture instead.
Or your location for number formatted, try this my source:
Ext:
public static class Ext
{
public static double? AsLocaleDouble(this string str)
{
var result = double.NaN;
var format = Thread.CurrentThread.CurrentUICulture.NumberFormat;
double.TryParse(str, NumberStyles.AllowDecimalPoint, format, out result);
return result;
}
}
Test:
class Program
{
static void Main(string[] args)
{
var str = "10,23";
Thread.CurrentThread.CurrentUICulture = new CultureInfo("uz-Cyrl-UZ");
Thread.CurrentThread.CurrentCulture = new CultureInfo("uz-Cyrl-UZ");
Console.WriteLine(str.AsLocaleDouble());
Console.ReadKey();
}
}

using numbers in a string

Can I use numbers while using String data type?
Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:
string numberAsString = "42";
int numberFromString;
if (int.TryParse(numberAsString, out numberFromString))
{
// number successfully parsed from string
}
TryParse will return a bool telling if the parsing were successful. You can also parse directly if you know the string contains a number - using Parse. This will throw if the string can't be parsed.
int number = int.Parse("42");
You can have numbers in a string.
string s = "123";
..but + will concatenate strings:
string s = "123";
string other = "4";
Debug.Assert(s + other != "127");
Debug.Assert(s + other == "1234");
Numbers can be easily represented in a string:
string str = "10";
string str = "01";
string str = 9.ToString();
However, these are strings and cannot be used as numbers directly, you can't use arithmetic operations on them and expect it to work:
"10" + "10"; // Becomes "1010"
"10" / "10"; // Will not compile
You can easily store numbers as a string:
string foo = "123";
but that only helps you if you actually want numbers in a string. For arithmetic purposes, use a number. If you need to display that later, us a format string.
String number1 = "123456";
keep in mind. using that number for arithmatic purpose, you have to convert that string into proper type like
int number1Converted = Int32.Parse(number1);
int.TryParse(number1 , out number1Converted );
for double
double doubleResult = 0.0;
double.TryParse("123.00", out doubleResult);

Categories