How can I convert string to decimal with trailing zero(s) - c#

Suppose that we have stringvalue=125.32600 when it convert to decimal value with this code
decimal d;
decimal.tryparse(stringvalue,out d)
d value is 125.326
how can I do this convert with final result 125.32600

You cannot because 125.32600 is equal to 125.326. In this case however I guess that you want to print it out with specific format, which can be done like this:
Console.WriteLine(d.ToString("f5"));
Read Standard Numeric Format Strings
UPDATE
Extension method:
public string Format(this decimal source, int precision)
{
if (precision < 0)
{
throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
}
return source.ToString("f" + precision);
}
which can be used like this:
Console.WriteLine(d.Format(5));

Your code works as written (as long as the decimal separator matches your culture):
decimal d;
decimal.TryParse("125.32600", NumberStyles.Number, CultureInfo.InvariantCulture, out d);
s = d.ToString(CultureInfo.InvariantCulture); // 125.32600
Decimal already remembers how many trailing zeros it has. This is caused by decimal representing numbers in non-normalized form, with an integer mantissa and an exponent representing the number of decimal digits. e.g. 125.32600 is represented as 12532600 * 10^-5

The answer is: You can't, at least not like that.
EDIT: correction: decimal already works like that; but you'll still find below a useful way to store your decimals in a DB.
Why? Because that's not how decimals are stored in memory.
Solution: if you need to keep the trailing zeros, just remember the precision explicitly in a separate field (of a class you should create for this purpose); or store the decimals in string form and only convert to decimal as needed.
string strValue = "125.32600";
int precision = strValue.Length - 1; // only the "12332600" part
decimal value = Decimal.Parse(strValue);
stores 8 in precision and 125.326 in value.
To get back the original form:
int afterPt = precision - ((int) value).ToString().Length;
Console.WriteLine(value.ToString("f" + afterPt));
prints
125.32600
P.S. you have to be aware of floating point binary representation issues though, so stuff like 4.05 might be stored as e.g. 4.049999999999999999, so if you need to guarantee this won't happen, use an algorithm that bypasses decimal altogether and uses only integers for storage and computation.
string strValue = "125.32600";
// parse and store
int value = int.Parse(strValue.Replace(".", ""));
int periodIx = strValue.IndexOf(".");
// get back the original representation
string str = value.ToString();
Console.WriteLine(str.Substring(0, periodIx) + "." + str.Substring(periodIx, str.Length - periodIx));
NOTE: Make sure to use , instead of . in locales that need it.

What you can do is count the zeroes in string and then store them in separate DB field. When you want the result with zeroes just concatenate the same no. of zeroes into decimal number string.
ex.
string p="123.456000";
int zeroes=p.Split('0').Length - 1; // guess
decimal value = Decimal.Parse(p); //without zeroes
string valWithZero=value.toString().padRight(zeroes,'0'); //with zeroes

If you really want to have the zeros in the database you could save it as a string, preformatted, but that would be very inefficient.
What is the problem you try to solve by this, there might be a better solution?

Related

C# Convert currency to string, remove decimal point but keep decimals, prepend 0s to have fixed width

How do I convert money amount like this
38.50
, to fixed width like this
000003850
I dont want to add commas and decimal places as some suggested answers here are explaining how to do. Neither do I want to remove decimals, I only want to remove decimal point.
You can use string.Format() with custom format specifiers. See details here.
double dollars = 38.50; // your value
int temp = (int)(dollars * 100); // multiplication to get an integer
string result = string.Format("{0:000000000}", temp);
// Output: 000003850
Figured it out thanks to #ReedCopsey at How to remove decimal point from a decimal number in c#?.
decimal amount = 38.50m;
int fixed_amount = (int)Math.Truncate(amount * 100);
Console.WriteLine(fixed_amount.ToString("D9"));
OUTPUT:
000003850

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

.NET: Shortest possible string representation of a double value

The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific notation. The problem is there still can be leading zeros in exponent.
Example:
Double d = 0.000001;
Console.WriteLine(d.ToString("G"));
1E-06
Is there a numeric format string that will remove leading zero in exponent so the result is
1E-6
I still want the function to return fixed-point notation if it is more compact. In other words, I want the shortest string representation of a double value.
edit: I would like to do it without post-processing
You can use post-processing to remove leading zeros.
static string Compact(double d)
{
var s = d.ToString("G");
if(s.Contains("E-0") || s.Contains("E+0"))
{
s = Regex.Replace(s, #"(\d+)(E[+-])0+(\d+)", "$1$2$3");
}
return s;
}
Usage
Console.WriteLine(Compact(0.000001)); // result: 1E-6
Console.WriteLine(Compact(12342353465345432313123123123.0)); // result: 1.23423534653454E+28
Console.WriteLine(Compact(0.000011)); // result: 1.1E-5
This can be done by using the longhand version of the formatting, and manually selecting the number of digits
Double d = 0.000001;
Console.WriteLine(d.ToString("0.###E-0"));
1E-6
The exact version I have made will round a number like 0.0000012351573 to 1.235E-6
If you really wanted the shortest you could techincally use
Console.WriteLine(d.ToString("0E-0"));
This will round it but always have only one digit- for example
Double d = 0.0000018;
Console.WriteLine(d.ToString("0.###E-0"));
2E-6

How to convert string to decimal with 3 decimal places?

string num = 23.6;
I want to know how can I convert it into decimal with 3 decimal places
like
decimal nn = 23.600
Is there any method?
I try my best..
First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";
If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);
decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);
Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.
Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.
string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600
There are two different concepts here.
Value
View
you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00.
you have string 23.6. you can convert it to decimal using var d = decimal.Parse("23.6")
now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")
you can read more about formatting decimal values
the thing that works for me in my case is num.ToString("#######.###")
A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:
decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

How to round and format a decimal correctly? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
I'm trying to get my decimals to display with four decimal places. The DB rounds my number to 4 decimal places, but it returns the number with trailing 0s (due to the decimal precision of the field), so something like 9.45670000. Then, when I do this:
string.Format("{0:#,#.####}", decimalValue);
The output I get on the page is 9.4567, which is what I want.
However, if the number returned from DB is 9.45600000, the output after doing the format is 9.456
But what I need to display is 9.4560
How do I format my decimal, so that the number of decimal places is always four?
UPDATE: Also, is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically?
string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
To set the precision dynamically you can do the following:
double value = 9.4560000;
int precision = 4;
string format = String.Format("{{0:N{0}}}",precision);
string valuestring = String.Format(format, value);
string.Format({0:#,#0.0000}, decimalValue);
Use String.Format -
decimal d =123.47
string specifier="{0:0,0.0000}"; // You need to get specifier dynamically here..
String.Format(specifier, d); // "123.4700"
Try this:
string.Format("{0:#,###.0000}", 9.45600000);
Adding the zeroes in the format forces a zero to be output if there is not a digit to put there.
To add the zeroes with the number of zeroes driven programmatically you could do this:
int x = 5;
string fmt = "{0:#,###." + new string('0', x) + "}";
string.Format(fmt, 9.456000000);

Categories

Resources