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');
Related
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);
}
}
Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."
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 am developing a program in the Marathi language. In it, I want to add/validate numbers entered in Marathi Unicode by getting their actual integer value.
For example, in Marathi:
४५ = 45
९९ = 99
How do I convert this Marathi string "४५" to its actual integer value i.e. 45?
I googled a lot, but found nothing useful. I tried using System.Text.Encoding.Unicode.GetString() to get string and then tried to parse, but failed here also.
Correct way would be to use Char.GetNumericValue that lets you to convert individual characters to corresponding numeric values and than construct complete value. I.e. Char.GetNumericValue('९') gives you 9.
Depending on your goal it may be easier to replace each national digit character with corresponding invariant digit and use regular parsing functions.
Int32.Parse("९९".Replace("९", "9"))
Quick hack of #Alexi's response.
public static double ParseValue(string value)
{
return double.Parse(string.Join("",
value.Select(c => "+-.".Contains(c)
? "" + c: "" + char.GetNumericValue(c)).ToArray()),
NumberFormatInfo.InvariantInfo);
}
calling ParseValue("१२३.३२१") yields 123.321 as result
I found my solution...
The following code will convert given Marathi number to its equivalent Latin number..
Thanks to #Alexei, I just changed some of your code and its working fine..
string ToLatinDigits(string nativeDigits)
{
int n = nativeDigits.Length;
StringBuilder latinDigits = new StringBuilder(capacity: n);
for (int i = 0; i < n; ++i)
{
if (char.IsDigit(nativeDigits, i))
{
latinDigits.Append(char.GetNumericValue(nativeDigits, i));
}
else if (nativeDigits[i].Equals('.') || nativeDigits[i].Equals('+') || nativeDigits[i].Equals('-'))
{
latinDigits.Append(nativeDigits[i]);
}
else
{
throw new Exception("Invalid Argument");
}
}
return latinDigits.ToString();
}
This method is working for both + and - numbers.
Regards Guruprasad
Windows.Globalization.DecimalFormatter will parse different numeral systems in addition to Latin, including Devanagari (which is what is used by Marathi).
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