As I saw in google, there are many implementation for string to an int or decimal... but not to a string.
For example:
decimal d1 = 32221.0210m;
Console.WriteLine(d1.ToString("#,###.00"));
This works but the problem is that I have a string and I don't want to cast it to a numeric.
string str = "32221.0210";
I want it to be:
str = "32,221.02";
Is it possible (without casting)?
For those who ask if is there any reason why not cast: Yes. I am using Infrastructures that receive a string. The infrastructures team don't want to convert it to decimal because they also may recieve another values such as date, etc...
In worse case, it is possible to TryParse decimal, so we know for sure it will work. But for now, we are trying to parse a string to a string as written above.
Thanks in advance :)
A temporary var of type decimal is required:
decimal d;
string str = decimal.TryParse("32221.0210", out d)? string.Format("{0:#,##0.00}", d):string.Empty;
Related
Im having alot of problems trying to take out the decimal part of my string,
the string comes from a var type in my view like this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro))**
temp.Rubro is my String part that can be ".00" or ".XX"
however i need to take the decimal part of the string only when its value is ".00"
since i have some values of the dashlist have important decimal parts.
Is there a way to take the decimal part of a string only if it equals to ".00"???
The output im trying to get is:
From XX.00 -> XX
From XX.12 -> XX.12
both kinds are on my list
Try this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro).Replace(".00", ""))
You can try using
String.Format("{0:G29}", decimal.Parse(temp.Rubro)))
Whereas all the below formats achieve the same results.
string.Format("{0:G29}", decimal.Parse("2.00"))
decimal.Parse("2.00").ToString("G29")
2.0m.ToString("G29")
You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).
Simple trick...
You can parse the string and it will automatically remove the decimal places
try following
private static void ParseDouble()
{
string sDouble = "12.00";
double dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
sDouble = "12.14";
dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
}
Your output will be
12
12.14
Hope this helps.
I will suggest you to use accounting.js plugging which is pretty straightforward. I have used it in some projects and as of today I cannot complain. Otherwise, you could do something like this,
var x = temp.Replace(".00","").Trim();
I'm beginner in c# and have this value of string:
123456
but want convert that string to my country money, want convert that string value to this:
123,456
always split three numbers with comma for example, if string number is this:
1234567890
Show to user this:
1,234,567,890
How can i write code that purpose?
I would suggest convert it to int (or long) first and then use ToString() and supply required format.
int number = int.Parse(numberString); //ex..
number.ToString("N0"); // 1,000,000
If you're asking about culture-specific formatting, then you could do this.
number.ToString("N0", CultureInfo.CreateSpecificCulture("es-US"));
You can explore more on standard numeric formats
Example code
Use the standard formatters and the CultureInfo for the desired country.
e.g
int i = int.Parse("123456");
string money = i.ToString("C", CultureInfo.CreateSpecificCulture("fr-Ir"));
Or if the system culture is fr-Ir
string money = i.ToString("C");
Which is the same as
string money = i.ToString("C", CultureInfo.CurrentCulture);
Or if you want to use the UI culture (the culture of the requesting browser)
string money = i.ToString("C", CultureInfo.CurrentUICulture);
Since you want to convert your value to currency, I would suggest using "C" of string formats provided by .NET.
123456.125M.ToString("C"); // $123,456.13
Sign infront of the string will be defined by the culture of your machine. More information here.
On the other hand, there is another solution to add your own custom format:
123456.125M.ToString("#,0.################"); // 123,456.125
It is not the clean way, but I have not since found a correct way of actually formating this in generic way.
Side note: for currency handling it is generally considered a good practise to use decimal. Since it does not have a floating point issue.
Please try this one hope will help
Just whats inside the void method
using System.Linq;
public class Program
{
public void ABC()
{
var data = "123456789";
const int separateOnLength = N;
var separated = new string(
data.Select((x,i) => i > 0 && i % separateOnLength == 0 ? new [] { ',', x } : new [] { x })
.SelectMany(x => x)
.ToArray()
);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading a double value from a string
I have a problem with converting my String into a double, I always get strange results.
I want to convert the following string:
string Test = "17828.571428571";
I tried it like this (because it normally works):
Double _Test = Convert.ToDouble(Test);
Result is: 17828571428571 (without the dot, lol)
I need it as a double, to Math.Round() afterwards, so I have 17828 in my example.
My second idea was to split the string, but is that really the best method? :S
Thanks for helping me!
Finn
Use InvariantCulture
Double _Test = Convert.ToDouble(Test,CultureInfo.InvariantCulture);
EDIT: I believe your current culture is "German" de-DE, which uses , for floating point.
Tried the following code. You may also use NumberFormatInfo.InvariantInfo during conversion.
string Test = "17828.571428571";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
double d = Convert.ToDouble(Test);
double d2 = Convert.ToDouble(Test, CultureInfo.InvariantCulture);
double d3 = Convert.ToDouble(Test, NumberFormatInfo.InvariantInfo);
string Test2 = "17828,571428571"; //Notice the comma in the string
double d4 = Convert.ToDouble(Test2);
Console.WriteLine("Using comma as decimal point: "+ d4);
Output: (Notice the comma in the output)
Wihtout Invariant: 17828571428571
With InvariantCulture: 17828,571428571
With NumberFormatInfo.InvariantInfo: 17828,571428571
Using comma as decimal point: 17828,571428571
double _Test = double.Parse(Test,CultureInfo.InvariantCulture);
You need to set the format provider of the conversion operation to invariant.
Try Double.TryParse or Double.Parse if you are sure there is the correct format
EDIT: But take care of the format. as example if you are german you need to type 140,50 and not 140.50 because 140.50 would be 14050.
Or you pass as parameter that you dont care of culture (see other posts).
I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?
Thanks.
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.
You can do:
string result = original.Substring(2);
decimal value = decimal.Parse(result);
Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.
Don't.
Instead, you should make .Net do the dirty work for you:
Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);
If, for some reason, you don't want a negative number, call Math.Abs.
All string operations return a new string, because string is immutable
I wouldn't use substring if you can avoid it. It would be much simpler to do something like:
string result = original.Replace("$", "").Replace("-", "");
As I'm working on C#, I have one field named 'Amount'.
double amount = 10.0;
So, I want the result like '10.0' after converting it to string.
If my value
amount = 10.00, then I want result '10.00' after converting it to string.
So, Basically I want exact result in string as it is in double type. (With precisions).
Thanks in advance.
string result = string.Format( "{0:f2}", amount );
What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.
string amountString = amount.ToString("N2");
"N2" is the format string used as the first parameter to the .ToString() method.
"N" stands for number, and 2 stands for the number of decimal places.
More on string format's here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
As #Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:
static public string GetPrecisionString( double doubleValue, int precision)
{
string FormattingString = "{0:f" + precision + "}";
return string.Format( FormattingString, doubleValue);
}