This question already has answers here:
Truncate Two decimal places without rounding
(24 answers)
Closed 7 years ago.
I have this variable:
Double dou = 99.99;
I want to convert it to a string variable, and the string should be 99.9.
I can do it like this:
string str = String.Format("{0:0.#}", dou);
But the value I got is: 100 which is not 99.9.
So how could I implement that?
PS: This question is marked as duplicated. Yes, they may have the same the solution (although I think that's a workaround), but from different viewpoints.
For example, if there is another variable:
Double dou2 = 99.9999999;
I want to convert it to string: 99.999999, so how should I do? Like this:
Math.Truncate(1000000 * value) / 1000000;
But what if there are more digits after dot?
You have to truncate the second decimal position.
Double dou = 99.99;
double douOneDecimal = System.Math.Truncate (dou * 10) / 10;
string str = String.Format("{0:0.0}", douOneDecimal);
You can use the Floor method to round down:
string str = (Math.Floor(dou * 10.0) / 10.0).ToString("0.0");
The format 0.0 means that it will show the decimal even if it is zero, e.g. 99.09 is formatted as 99.0 rather than 99.
Update:
If you want to do this dynamically depending on the number of digits in the input, then you first have to decide how to determine how many digits there actually are in the input.
Double precision floating point numbers are not stored in decimal form, they are stored in binary form. That means that some numbers that you think have just a few digits actually have a lot. A number that you see as 1.1 might actually have the value 1.099999999999999945634.
If you choose to use the number of digits that is shown when you format it into a string, then you would simply format it into a string and remove the last digit:
// format number into a string, make sure it uses period as decimal separator
string str = dou.ToString(CultureInfo.InvariantCulture);
// find the decimal separator
int index = str.IndexOf('.');
// check if there is a fractional part
if (index != -1) {
// check if there is at least two fractional digits
if (index < str.Length - 2) {
// remove last digit
str = str.Substring(0, str.Length - 1);
} else {
// remove decimal separator and the fractional digit
str = str.Substring(0, index);
}
}
Related
This question already has answers here:
Format string to a 3 digit number
(9 answers)
Closed 8 years ago.
I want to convert a number to a string but have the number formatted with 10 digits. For example, if the number is 5, the string should be "0000000005". I checked the formatting of strings at:
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx
but there isn't any format that lets you specify the number of digits.
Actually the "0" placeholder would work but in reality I need 100 places, so I'm not going to use the "0" placeholder.
You can use the ToString formatting Dn to output leading zeroes:
var d = 5;
var s2 = d.ToString("D2");
var s10 = d.ToString("D10");
Console.WriteLine(s2);
Console.WriteLine(s10);
The output is:
05
0000000005
Normally the D specifier for standard numeric format strings is enough with its precision to format a number with the required number of leading zeros.
But it stops at 99 and if you really need 100 leading zeros you need to resort to the old trusty method of string concatenation and right truncation
int number = 5;
string leadingZero = new string ('0', 100) + number.ToString();
string result = leadingZero.Substring(leadingZero.Length - 100);
This page should help you find the solution you need: http://msdn.microsoft.com/en-us/library/dd260048(v=vs.110).aspx
I want to have numbers with a fixed digit count.
example: 00001, 00198, 48484
I can do like this:
string value;
if (number < 10)
{
value = "0000" + number.ToString();
}
else if (number < 100)
{
value = "000" + number.ToString();
}
else if (number < 1000)
{
...
}
But this is a bit odd. Is there any built in function for my purpose?
Yes, there is:
string value = String.Format("{0:D5}", number);
According to the MS reference: http://msdn.microsoft.com/en-us/library/dd260048.aspx
You can pad an integer with leading zeros by using the "D" standard
numeric format string together with a precision specifier. You can pad
both integer and floating-point numbers with leading zeros by using a
custom numeric format string.
So:
To display the integer as a decimal value, call its ToString(String)
method, and pass the string "Dn" as the value of the format parameter,
where n represents the minimum length of the string.
Code:
string value = number.ToString("D5");
.NET fiddle: http://dotnetfiddle.net/0U9A6N
You should use the ToString() method with custom formating - see the docs. In particular the 0 specifier.
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
eg,
value = number.Tostring("00000");
string value = number.ToString("00000");
You can do it this way :
number.ToString("00000")
If you wish to return 5 digits numbers, you should use the PadLeft() function;
int Value = 101;
char pad = '0';
String sValue = Value.ToString();
sValue = sValue.s.PadLeft(5, char)
In this case, you don't have to test whether to add 1, 2 or 3 zeros, it'll automatically add the number of zeros needed to make it 5 digits number.
int input_number = Convert.ToInt32(txtinput.Text);
string number_value = input_number.ToString("00000");
I hope that it will solve your problem. It worked well for me in my previous project.
Test this code in your development. It should be worked properly without doubt.
Same as #Jojo's answer, but using C# 6's interpolated strings:
var value = $"{number:00000}";
Apart from String.Format, You can also use String.PadLeft
value = number.ToString().PadLeft(5, '0');
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?
I my application due to some reason I have two numbers in 5 digits.
The following code give you brief idea.
string s = "00001"; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + s;
//Operation end
//Increment the value of s by 1. i.e 00001 to 00002
This can be done easily by convert the value of s to int and increment it by 1 but after all that I have to also store the incremented value of s in 5 digit so it will be "00002".
This think give me a pain...
use
string s = "00001";
int number = Convert.ToInt32(s);
number += 1;
string str = number.ToString("D5");
to get atleast 5 digits.
The "D" (or decimal) format specifier
If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no
precision specifier is specified, the default is the minimum value
required to represent the integer without leading zeros.
This seems to work for me.
string s = "00001";
int i = Int32.Parse(s);
i++;
s = i.ToString("D" + s.Length);
So I think you want to know how to convert an int to a 5 digit string.
You can do this:
int i = 1;
string s = i.ToString("D5");
//s = "00001"
There are plenty of format examples here.
Use String.Format() to achieve this:
string str = String.Format({0:#####}, s);
Look here.
This works using the PadLeft function:
int i = 1; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + i.ToString().PadLeft(5, '0');
//Operation end
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);