How to check values numbers after the decimal point [duplicate] - c#

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 5 years ago.
I have tried looking for a similar question here but I can only find how to count the number of decimal places.
What I want to know is: how do I find the value of the decimal places that are >0?
For example, if we have:
decimal value = 1.920m;
decimal value2 = 1.900m;
How do I check if the values after the decimal point are >0?
I want to be able to check this and restrict the display accordingly so I can display something like this:
1.92
1.9

Essentially you want to display the value with the max number of decimal places available and remove the trailing zeros. This is the easiest way to do it:
Console.WriteLine(value.ToString("G29")); // Output 1.92
Alternate solution (which works for numbers smaller than 0.00001m unlike the above solution). Though this doesn't look as neat as the previous solution using G29, this works better since it also covers numbers smaller than 0.00001:
Console.WriteLine(value.ToString("0.#############################")); // Output 1.92
We are using G29 since 29 is the maximum available digits for a decimal. The G or General Format Specifier is used to define the maximum number of significant digits that can appear in the result string. Any trailing zeros are truncated using this format specifier. You can read more about it here.
Input: 1.900m
Output: 1.9
Input: 14.571428571428571428571428571M
Output: 14.571428571428571428571428571
Input: 0.00001000000m
Output: 1E-05 (Using first solution G29)
Output: 0.00001 (Using second solution)

If i understand you right you can do something like this:
double x = 1.92;
x-=(int)x;
while(x%1>0){
x*=10;
}
Console.WriteLine(x);
output:
92
now you can check what you want on this number

If you want to convert to decimal only use this
static decimal? RemoveTrailingZeros(this decimal? value)
{
if (value == null) return null;
var format = $"0.{string.Join(string.Empty, Enumerable.Repeat("#", 29))}";
var strvalue = value.Value.ToString(format);
return ConvertToDecimalCultureInvariant(strvalue);
}
static decimal? ConvertToDecimalCultureInvariant(this string value)
{
decimal decValue;
if (!decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decValue))
{
return null;
}
return decValue;
}
Since the precision of a decimal is 29 hence Enumerable.Repeat("#", 29).
And use it as
var result = RemoveTrailingZeros(29.0000m);

Related

How to convert a double value to string without rounded [duplicate]

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);
}
}

How to convert a number to a string but formatted with x number of digits [duplicate]

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

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

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?

Decimal to String Formatting [duplicate]

This question already has answers here:
Truncate Two decimal places without rounding
(24 answers)
Closed 9 years ago.
I try to convert (Decimal)0.9975 to string with (0.##) format in C# but it rounds the number to 1 instead of 0.99
Here is the code;
decimalValue.ToString("0.##");
How can I write the output as 0.99?
I got this on SO long time back. I too was struck with something similar. I owe this post to him.
decimal d = 0.9975m;
decimal newDecimal = Math.Truncate((d*100))/100;
string result = string.Format("{0:N2}", newDecimal.ToString()); // OR
string result = newDecimal.ToString(); //This is simpler I guess.
Hope it helps.
the other option is to accept the rounding but subtract 0.005 from the decimal
decimal d = 0.9975m;
string result = (d-0.005m).ToString("0.##");
(0.9975 - 0.005) = 0.9925;
0.9925 => 0.99
use format
decimalValue.ToString("#0.0#");
The '#' will be updated if there is a value on the placeholder, if there is no value on the'#' placeholder, then this will be ignored, but the '0.0' will not be ignored.
or
var value = string.Format("{0:0.00}", decimalValue);
or
decimal decimalValue = 0.9975;
value.ToString("G3");
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

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