C# decimal tostring format - c#

I want to create a string from a decimal, whithout the decimal separator;
1,500.00 should become "150000".
What is the proper format for this? (Whithout string.replace , and .)
Thank you!

try:
decimal d = 1500m;
string s = (100*d).ToString("0");

Two solutions:
Create your own NumberFormatInfo and CultureInfo and pass it along to ToString.
Multiply the number by 100, then use .ToString("0")

What's wrong with String.Replace anyway? It's simple and to the point:
CultureInfo info = CultureInfo.GetCultureInfo("en-US");
decimal m = 1500.00m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000"
m = 1500.0m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "15000"
m = 1500.000m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500000"
m = 1500.001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500001"
m = 1500.00000000000000000000001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000000000000000000000001"

decimal value = 1500;
Console.WriteLine((value * 100).ToString("0"));

Related

double.ToString() return wrong value in C#

I have double variable and its value is :
double d = 0.000000000000056843418860808015;
when i print this variable its print wrong.
d.ToString();
Output : "5.6843418860808E-14"
How to resolve this?
Well if you want to have an output without the exponential notation you need to format your string:
d.toString("F25");
This will give you the "correct" number with up to 25 fractional digits.
0,0000000000000568434188608
Edit: Complete list of formats and conversions are available here and snapshot for you is below.
Original value: 1054.32179
F: 1054.32
F0: 1054
F1: 1054.3
F2: 1054.32
F3: 1054.322
double d = 0.000000000000056843418860808015;
var str = d.ToString("G17");
var value = str.Split('E')[0];
var zeros = Int32.Parse(str.Split('E')[1]);
var outputString = "";
zeros = Math.Abs(zeros);
var addstring = "0.";
for (var i = 0; i < zeros - 1; i++)
{
addstring += '0';
}
value = value.Remove(1, 1);
value = addstring + value;

Convert string with format X.X.X to float

I'm grabbing some data for a project that gives me a string in format X.X.X (example 15.23.1) which I need to somehow get down to 15.231. I thought I could convert the original string into a float and then use Convert.ToSingle to get it into a float but my attempts so far are failing.
Anyone got an easy solution for this?
Just remove the last . and then parse the rest of the string using float.Parse or float.TryParse
string str = "15.23.1";
str = str.Remove(str.LastIndexOf('.'), 1);
float f;
if (float.TryParse(str, out f))
{
Console.WriteLine("Parsing successful");
}
else
{
Console.WriteLine("Parsing failed");
}
If you want Culture Insensitive parsing then you can try:
if (float.TryParse(str, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out f))
This will throw an exception if str has an unexpected format.
float f = float.Parse(str.Remove(str.LastIndexOf('.'), 1), CultureInfo.InvariantCulture);
Option with regex:
string str = "14.4.6";
str = Regex.Replace(str, #"(\d+)(\.\d+)?\.?(\d+)?", "$1$2$3");
// parse string
Samples of input and output:
15.23.1 > 15.231
15.23 > 15.23
15 > 15
Looks like you just need to use String.Remove and String.LastIndexOf methods like;
string s = "15.23.1";
s = s.Remove(s.LastIndexOf('.'), 1);
float f;
if(float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out f))
{
Console.WriteLine("YES");
Console.WriteLine(f);
}
else
{
Console.WriteLine("NO");
}
Output will be;
15,231

How to format string to money

I have a string like 000000000100, which I would like to convert to 1.00 and vice versa.
Leading zero will be remove, last two digit is the decimal.
I give more example :
000000001000 <=> 10.00
000000001005 <=> 10.05
000000331150 <=> 3311.50
Below is the code I am trying, it is giving me result without decimal :
amtf = string.Format("{0:0.00}", amt.TrimStart(new char[] {'0'}));
Convert the string to a decimal then divide it by 100 and apply the currency format string:
string.Format("{0:#.00}", Convert.ToDecimal(myMoneyString) / 100);
Edited to remove currency symbol as requested and convert to decimal instead.
you will need to convert it to decimal first, then format it in money format.
EX:
decimal decimalMoneyValue = 1921.39m;
string formattedMoneyValue = String.Format("{0:C}", decimalMoneyValue);
a working example: https://dotnetfiddle.net/soxxuW
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console output:
It works!
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
Output
Order Total: $1,921.39
Once you have your string in a double/decimal to get it into the correct formatting for a specific locale use
double amount = 1234.95;
amount.ToString("C") // whatever the executing computer thinks is the right fomat
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95
Try simple like this
var amtf = $"{Convert.ToDecimal(amt):#0.00}";
string s ="000000000100";
decimal iv = 0;
decimal.TryParse(s, out iv);
Console.WriteLine((iv / 100).ToString("0.00"));
//Extra currency symbol and currency formatting: "€3,311.50":
String result = (Decimal.Parse("000000331150") / 100).ToString("C");
//No currency symbol and no currency formatting: "3311.50"
String result = (Decimal.Parse("000000331150") / 100).ToString("f2");
you can also do :
string.Format("{0:C}", amt)
Try something like this:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
In my case, I used this string format to display currency from decimal values without the symbol.
String format:
string.Format("{0:#,##0.00}", decimalValue)
Example:
var decimalNumbers = new decimal[] { 1M, 10M, 100M, 1000M,10000M,100000M,1000000M,1000000000M };
foreach (var decimalNumber in decimalNumbers)
{
Console.WriteLine(string.Format("{0:#,##0.00}", decimalNumber));
}
Parse to your string to a decimal first.
var tests = new[] {"000000001000", "000000001005", "000000331150"};
foreach (var test in tests)
{
Console.WriteLine("{0} <=> {1:f2}", test, Convert.ToDecimal(test) / 100);
}
Since you didn't ask for the currency symbol, I've used "f2" instead of "C"
try
amtf = amtf.Insert(amtf.Length - 2, ".");
private string cxp(string txt) {
try
{
decimal n;
n = Math.Round( Convert.ToDecimal( txt),2);
string newTxt;
newTxt = Convert.ToString(n);
//txt = txt.Replace(",", ".");
//string newtxt = string.Format("{0:#.00}", Convert.ToDecimal(txt) );
return newTxt.Replace(",", ".");
}
catch (Exception e)
{
MessageBox.Show(e.Message ,"Error al parsear número");
//throw;
return txt;
}
}

How do I capture this latitude value in regex?

I'm calling a service that gives me back a latitude and longitude like this: "Lat:42.747058 Long:-84.551892".
How do I capture the latitude value using regular expressions?
This code does not work.
string GPSLocation = "Lat:42.747058 Long:-84.551892";
MatchCollection matches = Regex.Matches(GPSLocation, "Lat:() ");
if (matches.Count > 0)
{
string latValue = matches[0].Value;
return Decimal.Parse(latValue);
}
return 0M;
Try this regex:
(?<=Lat:)(-?\d+\.\d+)
In C#:
Regex.Matches(GPSLocation, "(?<=Lat:)(-?\\d+\\.\\d+)")[0].Value;
It simply matches a decimal number with an optional --sign.
I wouldn't use regex for something simple like this
How about
string GPSLocation = "Lat:42.747058 Long:-84.551892";
var values = GPSLocation.split(" ");
if (values.Count > 0)
{
string lat = values[0].split(":")[1];
return Decimal.Parse(lat);
}
return 0M;
Hope you don't mind me putting a non-regex solution
string GPSLocation = "Lat:42.747058 Long:-84.551892";
string lat = GPSLocation.Substring(4, GPSLocation.IndexOf("Long") - 5);
string lon = GPSLocation.Substring(GPSLocation.IndexOf("Long") + 5);
"Lat:()" will match "Lat:", then capture an empty string. Inside the parentheses you need to add the characters you want to capture, like this: "Lat:([-.0-9]*)".
This should work:
Lat:([\d.-]+) Long:([\d.-]+)
with this String:string GPSLocation = "Lat:42.747058 Long:-84.551892";You can first use Split(':') then Use Split(' '): string s=GPSLocation.Split(':')[1].Split(' ')[0] then s Lat.
Try:
string GPSLocation = "Lat:42.747058 Long:-84.551892";
string latRegex = "Lat:-?([1-8]?[1-9]|[1-9]?0)\\.{1}\\d{1,6}"
MatchCollection matches = Regex.Matches(GPSLocation, latRegex);
if (matches.Count > 0)
{
...
Regex shamelessly stolen from RegexLib.com
Make sure to double up on your backslashes
With use of a regex object which you could compile and use again and again.
Decimal res;
string GPSLocation = "Lat:42.747058 Long:-84.551892";
Regex regexObj = new Regex(#"(?<=Lat:)-?(\b[0-9]+(?:\.[0-9]+)?\b)");
if (Decimal.TryParse(regexObj.Match(GPSLocation).Groups[1].Value, out res)){
return res;
}
return 0M;

String format and hex chars

can someone explain why this doesnt work:
string f = string.Format("\\x{0:00}{{0}}", 5);
string o = string.Format(f, "INSERT TEXT");
System.Diagnostics.Debug.WriteLine(f + " : " + o);
Output is:
\x05{0} : \x05INSERT TEXT
why does the \x05 not get replaced?
The format for the argument should be set in the format specifier, otherwise you're just inserting a literal "\x". Like this:
// "5" as a lowercase 2-digit hex
string f = string.Format("{0:x2}{{0}}", 5);
Don't confuse how you represent a hex literal in source code with what you would print in a formatted string, they are different things.
To put a literal char in a string, just make sure that the compiler knows it's a char.
string f = string.Format("{0}", (char)5);
string g = string.Format("{0}", Convert.ToChar(5));
string h = string.Format("{0}", char.ConvertFromUtf32(5));
or you can start out with a real char:
string i = string.Format("{0}", '\x05');
string j = string.Format("{0}", '\u0005');
string k = string.Format("{0}", '\U00000005');
Take your pick.
Is this what you need?
int x = 5;
string f = string.Format("\\x{0:x2}{1}", x, "INSERT TEXT");
Console.WriteLine(f);

Categories

Resources