How do I keep the trailing zeroes like the example below. When I input -.230 with no leading zeroes it only displays -0.23 without the trailing zero. But when I input -0.230 it yields the expected result which is -0.230.
Actual output: -.230 -> -0.23
Expected output: -.230 -> -0.230
I have also tried String.Format("{0:0.000}", n) but it still does not work.
Looks like you are converting to string so you can use the following
someNumber.ToString("N3");
See the MSDN docs for details on how this works, about halfway down the page it also has examples of a bunch of different codes.
It seems that you are print the same number on which you have performed string.format.
Try to store the output of string.format and use that. I have used the same approach that you have used and got the expected answer. Refer following code
var n = -.23;
string str = string.Format("{0:0.000}", n);
Console.WriteLine(str); // This will give you an expected output
Console.WriteLine(n); // This won't give you an expected output
double and decimal mentioned in the question, are quite different types. double is a binary floating point value and it doesn't keep trailing zeroes:
double value = -0.230;
Console.Write(value); // -0.23
Unlike double, decimal being decimal floating-point does store the trailing zeroes:
decimal value = -0.230m; // note suffix "m"
Console.Write(value); // -0.230
When represented as string values of these types can be formatted, e.g. with F3
format string which stands for "3 digits after the decimal point":
double v1 = -0.230;
decimal v2 = -0.230m;
Console.Write($"{v1:f3} {v2:f3}");
Outcome:
-0.230 -0.230
Related
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
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);
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 have a senario where I am converting numbers to words and I have suceeded in it, but I found one scenario where it's not working. If I enter the number as "10", it displays "ten". Also, "10.2" will display "ten point two". However, if I enter "10.0" it will not display as "ten point zero".
For seperating the whole number part from the decimal part I usually split the number by '.', but if I enter a number like "10.0", the string array will contain only "10" and not the "0"
The spitting part which I have done is given below:
string[] number = Convert.ToString(context.NumberToTranslate).Split('.');
To test if your number is an integer w/o decimal point you could try and parse it with
int tmpInt;
bool isInteger = Int32.TryParse(num.ToString(), out tmpInt);
If it is an integer just convert the number to your string representation otherwise preserve the digit after the decimal point no matter what using a custom format string:
string number = num.ToString("#.0");
The same issue can arise if your number is less than 1, so you can use the zero placeholder for the digit before the decimal point as well:
string number = num.ToString("#0.0");
Also see Custom Numeric Format Strings
Actually numbers after point is lost if the number, even i the number is a Float or Double.
The solution is to use decimal Type for these numbers, it preserves the 0 after decimal.
Example:
Console.WriteLine(Convert.ToString(10.0M));
Output:
10.0
Febin:
It seems like an order of operations issue. Try doing the splitting before the converting"
var parts = ("10.0").Split('.'); //or context.NumberToTranslate
parts[0] //"10"
parts[1] //"0"
//Convert
string[] number = Convert.ToString(parts);
You don't have to break it out completely, but I did that to show you can split "10.0" and then do what you want with it.
One thing you could do is compare your number to itself cast to an integer to determine if you need to append zero to the string that you're generating.
Something along the lines of:
var n = 10.0f;
if(n == (int)n) {
Console.WriteLine("zero");
}