How to put decimal point in a whole number - c#

I'm reading a text file from bank with a string of numbers. 0000000010050, the amount of this string is $ 100.50, but is there a way to insert a decimal point in the string? here is my code.
string amount = 0000000010050;
string f_amount = "";
string ff_amount = "";
decimal d_amount = 0;
f_amount = amount.Trim();
d_amount = int.Parse(f_amount.TrimStart('0')); // this part removes the zeros and the output is 10050.
ff_amount = string.Format("{0:0,0.00}", d_amount); // this line outputs 10050.00
how to make the output looks like this 100.50?

First convert the string to decimal and apply string.Format in this way
string.Format("{0:#.00}", Convert.ToDecimal(bankString) / 100);
this will give the result 100.50
https://dotnetfiddle.net/WrRVFo

Something like this (let's take CultureInfo into account)
using System.Globalization;
...
string amount = "0000000010050";
amount = amount
.Insert(amount.Length - CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits,
CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator)
.TrimStart('0');

Related

How to parse, actually get number from string in c#?

I am trying to get only part with number. For example in input could be just number like 50, or string like: 50 and more. Also Number always will be on first place. And I want always to get only number from that. I tried like this, but this does not work:
double tendency;
var tendencyToString= Convert.ToString(tendency.ToString());
var tendencySplited = tendencyToString.Split(' ');
var tendencyNumber = tendencySplited[0];
You can extract the number from the string using a regular expression.
See an example below. One thing to pay an attention to are your locale settings as they influence the format of the double.
string pattern = #"^\d+\.\d+";
string input = "50.1 , or more";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success) {
double nr = Double.Parse(m.Value);
Console.WriteLine(nr);
}
So if i enter "507.89foo123,456bah" you want only 507 or you want
507.89? –
Please read, I write 50, not 50 with coma or something decimal. I just want 507 in your example
Well, then it's pretty easy:
string input = "50.1 , or more";
char[] digits = input.TakeWhile(Char.IsDigit).ToArray();
if(digits.Any())
{
string result = new string(digits); // "50"
// if you want an integer:
int number = int.Parse(result);
}

How to compare currency or alphanumeric values in C#

The value that extracted from the application is in string format for ex. "$0.38". So, I segregated each character in the given string using IsDigit then appended them together using string builder. The digit can also be alphanumeric like "12,365.23 AS". Is there a way to recover only numeric part (along with the decimal) from the given string.
But Output I receive is "38" instead of "0.38". I also want to compare that the given string value lies between the upperLimit and lowerLimit provided.
Please let me know how to proceed with the same.
string Value = "$0.38";
int upperLimit = 2500;
int lowerLimit = 50000;
StringBuilder sb = new StringBuilder();
//sb.Append(someString);
foreach (char amin in Value)
{
if (System.Char.IsDigit(amin))
{
sb.Append(amin);
}
}
int compareVal = Convert.ToInt32(sb.ToString());
Console.WriteLine("value for comparision" + " " + compareVal);
The best way is using one of the overloads of decimal.Parse:
string Value = "$0.38";
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
decimal dd=decimal.Parse(Value, System.Globalization.NumberStyles.AllowCurrencySymbol|System.Globalization.NumberStyles.AllowDecimalPoint,culture);
Note the use of NumberStyles enum.That way you can control exaclty the parsing.
There are two reasons why you will get 38:
StringBuilder looks like "038", since "." is not a digit (just like "$").
Convert.ToInt32(...) returns an integer which doesn't allow decimal digits.
The better data type for currencies is decimal, a high precision floating point data type so to say.
Try
var amount = decimal.Parse(Value , NumberStyles.Currency)
var isInLimit = upperLimit <= amount && amount <= lowerLimit; // i guess you swapped upper and lower limit btw. ;)
instead.
Edit
In order to use the NumberStyles-Enumeration, you will have to use tha correct namespace in your file:
using System.Globalization;
You are omitting the decimal point and you are not using a decimal data type to hold the converted value. The real way to go is to convert the currency string to a decimal number:
CultureInfo usCulture = new CultureInfo("en-US)";
decimal amount = decimal.Parse(Value, NumberStyles.Currency, usCulture);
You can then perform a proper numeric comparison:
if (amount <= upperLimit && amount >= lowerLimit)
....
I first marked the question as a duplicate, but then changed my mind. I still think it is very much related to: Convert any currency string to double

How do I parse string with decimal separator to a double c#?

How to get correct double digit from string.
string first = "23.3";
string second = "23,3";
For now I used the sample parser for parse the number in double format:
double number = double.Parse(first);
double another = double.Parse(second);
So if I used en-US culture and for decimal separator used '.' then the result will be number = 23.3 and another = 233.
So my question is do is possible to ignore the decimal separator and when is parse in both case to return result = 23.3.
In addition to replace comma with dot, you need to supply a proper number format:
public double ParseMyString(string myString)
{
return double.Parse(myString.Replace(',', '.'),
new NumberFormatInfo() {NumberDecimalSeparator = "."});
}
Another option to replace the separator on a broader scope is to use this:
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
You will still need to replace comma with dot though.
You can play a trick:
private string ReplaceSeparator(string Num)
{
return Num.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}
.....
string first = "23.3";
string second = "23,3";
first = ReplaceSeparator(first);
second = ReplaceSeparator(second);
double number = double.Parse(first);
double another = double.Parse(second);

Convert decimal currency to comma separated value

I get from a webservice the following strings:
12.95
or
1,200.99
Is there an option to convert these values to the following values without manipulating the string?
12,95
or
1200,99
I tried it with some Culture options but didn't get it right...
EDIT
I tried this:
//return string.Format( "{0:f2}", Convert.ToDecimal( price ) );
//return string.Format(CultureInfo.GetCultureInfo("de-de"), "{0:0}", price);
NumberFormatInfo format = new System.Globalization.NumberFormatInfo();
format.CurrencyDecimalDigits = 2;
format.CurrencyDecimalSeparator = ",";
format.CurrencyGroupSeparator = "";
return decimal.Parse(price).ToString(format);
var input = "1,200.99";
//Convert to decimal using US culture (or other culture using . as decimal separator)
decimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));
//Convert to string using DE culture (or other culture using , as decimal separator)
string output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(output); //1200,99
What about something like this:
double number;
double.TryParse("1,200.99", NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out number);
var formattedNumber = number.ToString(CultureInfo.CreateSpecificCulture("de-DE"));
Then return or write out formattedNumber (whatever you need to do).
Yes and no. First, what you have is a string, and so you cannot change the formatting of it as you're attempting to. However, to achieve what you would like, you can parse the string into a decimal value and then use the formatting options for decimals to display it in any reasonable way.
You may try for something like this:
String.Format("{0:#,###0}", 0);
or may be like this:
string str = yourNumber.Remove(",").Replace(".",",");
Close enough tronc,
Try this snippet:
String curStr = "12.95";
Decimal decVal;
var valid = Decimal.TryParse(curStr, out decVal);
if (!valid) throw new Exception("Invalid format.");
String newFormat = decVal.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));
Within the toString(...) call, you can append a number after 'C' to specify how many decimal places should follow. E.g "C3".

Convert double to string, keep format - C#

Hi all. I have a double number (Ex: 0.000006). I want convert it to string type. But result is "6E-06". I dont want it, i want 0.000006".Thanks you so much
double a = 0.000006;
string resultString = a.toString();
I don't know many number after "." character
It's simple that if you want to show a number as exactly as what it looks, we can cast it to decimal and use the default ToString() like this:
var s = ((decimal)yourNumber).ToString();
//if yourNumber = 0.00000000000000000000000006
//just append the M after it:
var s = (0.00000000000000000000000006M).ToString();
Please check this article and find the format which suits your needs: http://www.csharp-examples.net/string-format-double/
Looks like this one is good enough:
String.Format("{0:0.00}", 123.4567);
Use String.Format() with the format specifier.
double a = 0.000006;
string formatted = String.Format("{0:F6}", a);
Try with the Roundtrip 'R' format specifier:
double a = 0.000006;
string resultString = a.ToString("R");
Double Rate_USD = Convert.ToDouble(txtRateUsd.Text);
string Rate_USD = txtRateUsd.Text;

Categories

Resources