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
Related
This question already has answers here:
Adjusting decimal precision, .net
(7 answers)
Closed 4 years ago.
I am diving 2 decimal number and want value upto 5 precision. below is my code.
decimal postiveTotal = 3,totalLenght = 6;
decimal postiveFractionResult = postiveTotal / totalLenght;
I m expecting 0.50000 but I am getting 0.5
C# number display type like decimal will always strip the appended 0 - there is no difference between 0.5 and 0.50.
If you want to have the output correctly formatted you need to use a string format identifier:
Custom number format identifier:
Console.WriteLine($"{postiveFractionResult:0.00000}");
Standard number format identifier:
Console.WriteLine($"{postiveFractionResult:F5}");
Assignment to variables:
// using string interpolation
string result = $"{postiveFractionResult:0.00000}";
// using string.format explicite
string result = string.Format("{0:0.00000}", postiveFractionResult);
You can find more information on string format here.
Standard Numeric Format
Custom Numeric Format Strings
EDIT
As noted by Daisy Shipton there is a difference when declaring a variable either by 0.5M or 0.50M. A little test with the different declaration shows that the additional defined 0 is also preserved through calculation:
var result = 1.25m * 0.5m; // 6.25M
var result1 = 1.250m * 0.5m; // 0.6250M
var result2 = 1.250m * 0.50000m; // 0.62500000M
var result3 = 1.25000m * 0.5m; // 0.625000M
var result4 = 1.25000m * 0.50000m; // 0.6250000000M
Please see also the following so post which has an explanation about this behavior. Sadly the links are broken and I could not find the correct ECMA link due to the website being currently offline.
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);
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
This question already has answers here:
Convert from scientific notation string to float in C#
(2 answers)
Closed 9 years ago.
I want to convert a very Small number to Decimal,
Lets Say
String secondsStr = 0;
Decimal secondsValue;
Boolean success = Decimal.TryParse(secondsStr, out secondsValue);
But the problem is I have the string representation of it, 3.24E-08
String secondsStr = 3.24E-08;
Decimal secondsValue;
Boolean success = Decimal.TryParse(secondsStr, out secondsValue);
It always return success as false.
How can I parse that to get 0.00000003244657 ?
You can use TryParse with the NumberStyles argument:
var ok = Decimal.TryParse(secondsStr, NumberStyles.Any, null, out secondsValue);
I have used NumberStyles.Any which works.
Indicates that all styles except AllowHexSpecifier are used. This is a
composite number style.
Update: if it works with NulberStyles.Float depends on the current culture. If it uses . as decimal separator it works. So you can also use CultureInfo.InvariantCulture as third argument:
var ok = Decimal.TryParse(secondsStr, NumberStyles.Float, CultureInfo.InvariantCulture, out secondsValue);
Try this
Boolean c= decimal.TryParse("3.24E-08", System.Globalization.NumberStyles.Float, null, out a);
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);