Math.Floor Behaviour - c#

double c, d, e;
double a = (c - d) / e;
double b = Math.Floor(a);
Debug.WriteLine(a.ToString() + " " + b.ToString());
Code above outputs "3 2" at one configuration where all numbers are double. How is this possible? Is it because of fractional error resulting from double operations? However I think a.ToString() should give the whole number with its fractional part.

It's just a matter of what double.ToString() does. Here's a short but complete program demonstrating the same thing:
using System;
public class Test
{
static void Main(string[] args)
{
// Find the largest double less than 3
long bits = BitConverter.DoubleToInt64Bits(3);
double a = BitConverter.Int64BitsToDouble(bits - 1);
double b = Math.Floor(a);
// Print them using the default conversion to string...
Console.WriteLine(a.ToString() + " " + b.ToString());
// Now use round-trip formatting...
Console.WriteLine(a.ToString("r") + " " + b.ToString("r"));
}
}
Output:
3 2
2.9999999999999996 2
Now double.ToString() is documented with:
This version of the ToString method implicitly uses the general numeric format specifier ("G") and the NumberFormatInfo for the current culture.
... and the general numeric format specifier docs state:
The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table.
... where the table shows that the default precision for double is 15. If you consider 2.9999999999999996 rounded to 15 significant digits, you end up with 3.
In fact, the exact value of a here is:
2.999999999999999555910790149937383830547332763671875
... which again, is 3 when regarded with 15 significant digits.

Related

Why ADecimalNumber.ToString("#,##0") round the number?

C#: I have a decimal number, I want to separate the thousand numbers by a comma but not round the number. As answers of stack overflow, I used .ToString("#,##0") but it rounds the number. It's not acceptable for me to round the number!
In my model I have:
public decimal? ADecimalNumber { get; set; }
In Controller I have:
ViewBag.ADecimalNumber = result?.ADecimalNumber;
And in View I have:
#(ViewBag.ADecimalNumber != null ? ViewBag.ADecimalNumber.ToString("#,##0") : '-')
The ViewBag value is 11106.8314M in quick-watch mode, and the ViewBag.ADecimalNumber.ToString("#,##0") result is "11,107".
It's default behavior of custom specifier. See The "#" Custom Specifier.
The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.
Rounding is part of the behavior of the # custom digit formatter. Use Math.Truncate() to cut off the digits after the period if you do not want rounding:
Math.Truncate(ViewBag.ADecimalNumber).ToString("#,##0")
If you want to print n decimal places though, multiply the number with the nth-power of 10, truncate, then divide by that same power, for example: Math.Truncate(123456.78M * 10M)/10M will give 123456.7 which you could print using the format string #,###.#

Show double as percentage without decimals with ToString method

Looking for:
95,4545454545455 -> 95 %
I tried using:
String resultAsPercentage = result.ToString("##0 %");
But, it shows
9545 %
Then, I solved my problem using regex:
Question: Why my ToString method hasn't worked? And how to fix it to avoid using regex?
Thanks in advance.
As documented on Custom Numeric Format Strings, the % modifier multiplies the value by 100 before inserting the %. It's intended to be used with fractions. To disable this special meaning of %, escape it by preceding it with #"\".
Alternatively, you could take the % out of the format string, and append it manually: result.ToString("##0") + " %".
If you don't care about rounding, you can use the following:
double result = 95.4545454545;
String resultAsPercentage = (int)result + " %";
System.out.println(resultAsPercentage);
Output is: 95 %
Casting to an int drops the decimal places without rounding
You can use thew P(ercentage) format specifier, you need to divide through 100 because the specifier multiplies it by 100:
decimal value = 95.4545454545455m;
String resultAsPercentage = (value / 100).ToString("P0"); // 95%
If you need the space between the value and the percentage symbol you could use this approach:
NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
nfi.PercentSymbol = " %";
String resultAsPercentage = (value / 100).ToString("P0", nfi); // 95 %
One way can be Clone a culture (like InvariantCulture), set it's PercentPositivePattern to 0, divide your value by 100 and get it's string representation using The percent ("P") format specifier with 0 precision and that cloned culture as;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.PercentNegativePattern = 0;
Console.WriteLine(((int)95.4545454545455 / 100.0).ToString("P0", clone)); // 95 %
You can see all associated patterns on Remarks section on that page.
You can guaranteed to set PercentNegativePattern property as well for negative values.

Format decimal value to string with leading spaces

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?
For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"
I'm looking for a solution, that works with standard/custom string formatting, i.e.
decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.
This pattern {0,5:###.0} should work:
string.Format("{0,5:###.0}", 12.3456) //Output " 12.3"
string.Format("{0,5:###.0}", 10.011) //Output " 10.0"
string.Format("{0,5:###.0}", 123.123) //Output "123.1"
string.Format("{0,5:###.0}", 1.123) //Output " 1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"
Another one with string interpolation (C# 6+):
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
Expression returns: " 123.4560"
value.ToString("N1");
Change the number for more decimal places.
EDIT: Missed the padding bit
value.ToString("N1").PadLeft(1);
Many good answers, but this is what I use the most (c# 6+):
Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 => " 1.23"
//if height is 0.23 => " 0.23"
//if height is 123.23 => "123.23"
All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding
decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99
Note the "." could be a "," depending on Region settings, when using string.Format.
string.Format("{0,5:###.0}", 0.9) // Output " .9"
string.Format("{0,5:##0.0}", 0.9) // Output " 0.9"
I ended up using this:
string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example " 0", " 3000", and "24000"
string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example " 2.3"
Thanks a lot!

Problem with C# double format

I am using next code to format double value:
String.Format("${0:0,0.#}",...);
It working great, but when numbers are less than 10, I got problem. Numbers are displayed as $03, $06 for example.
Please advise me correct string to have a double number in next format ddd,ddd,ddd,ddd.dd
Try this instead:
string result = string.Format("${0:#,##0.00}", d);
If your double represents a currency you should use:
string result = string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:c}", d);
Note that if you omit the CultureInfo.InvariantCulture it could display using something other than $ on some computers. For example on my computer string.Format("{0:c}", d) gives 2,00 kr which might not be what you wanted.
In your example you don't actually need to use string.Format at all. You could use this instead:
string s = d.ToString("c", CultureInfo.GetCultureInfo("en-US"));
As well as being clearer and more concise, it also has the advantage of avoiding boxing. Of course if your format string is more complex than in your example then it would make sense to use string.Format.
And as a final remark I'd recommend against using doubles to store currency. A decimal type is probably more appropriate.
Use currency formatting:
String.Format("{0:C}", money);
String.Format("{0:C}", myDecimal);
or
myDecimal.ToString("C");
will display to two decimal places, include the comma separator and include the dollar sign (based on culture settings) in one fell swoop. If you want it to go to 1 or more than 2 decimal places, include a number after the C (i.e. C3)
Digits after decimal point
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
Some funny examples
String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"
String.Format("${0:#,0.#}",...);
should do it.
See Custom Numeric Format Strings

Remove 0s from the end of a decimal value [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 9 years ago.
I have a decimal value that has a variable number of digits after the ., for example:
0.0030
0.0310
0.0001
1.1200
How can I write a dynamic function that removes 0 in the end of the decimal?
You can also modify the decimal itself so that any ToString() will give you what you want
(more details in my answer here) :
public static decimal Normalize(decimal value)
{
return value/1.000000000000000000000000000000000m;
}
string.Format("{0:0.#####}", 0.0030)
or
var money=1.3000m;
money.ToString("0.#####");
For future reference I recommend the .NET Format String Quick Reference by John Sheehan.
decimal value = 0.0030m;
value.ToString(“G29″);
Edit: The G formatter does work, the only problem is that it jumps to scientific notation if there are too many significant figures in the original decimal. Not so ideal.
See the "The General ("G") Format Specifier" documentation here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
I'm on lunch, so I did a little test:
decimal d1 = 0.000100m;
decimal d2 = 0.001000000000000000000000m;
decimal d3 = 0.000000000000001000000000m;
Console.WriteLine(Environment.NewLine + "input decimal: 0.000100m");
Console.WriteLine("G " + d1.ToString("G"));
Console.WriteLine("G29 " + d1.ToString("G29"));
Console.WriteLine("0.####### " + d1.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.001000000000000000000000m");
Console.WriteLine("G " + d2.ToString("G"));
Console.WriteLine("G29 " + d2.ToString("G29"));
Console.WriteLine("0.####### " + d2.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.000000000000001000000000m");
Console.WriteLine("G " + d3.ToString("G"));
Console.WriteLine("G29 " + d3.ToString("G29"));
Console.WriteLine("0.####### " + d3.ToString("0.#######"));
Output:
input decimal: 0.000100m
G 0.000100
G29 0.0001
0.####### 0.0001
input decimal: 0.001000000000000000000000m
G 0.001000000000000000000000
G29 0.001
0.####### 0.001
input decimal: 0.000000000000001000000000m
G 0.000000000000001000000000
G29 1E-15
0.####### 0
Hmm, this is a display formatting issue (the zeros are added when you convert the decimal to a string).
You need to see where in code you are seeing the trailing zeros. Is it after a call to .ToString()? Try playing around with the different formatting strings:
.ToString("#");
.ToString("0.00");
.ToString("#.##");
And so on. The best way to do this is just to experiment with the different possible values.
decimal m = 0.030000m;
Console.Write(m.ToString("0.##########"));
Just make sure you have enough #s for the number of decimal places you want to display
I use the following. It ensures that any decimal (for which the max precision is 29 decimal places) will show all available digits of precision without trailing zeros, and without your code needing to have a long ugly string of hash marks.
if (value is Decimal)
value = ((Decimal)value).ToString("0.".PadRight(29, '#'), culture);
public static string GentlyRemoveEndZeros(string input)
{
// if (input == null) return null;
// if (input == "") return "";
if (input.Contains(".")) return input.TrimEnd('0').TrimEnd('.');
return input;
}

Categories

Resources