Best way to display decimal without trailing zeroes
Do you have a maximum number of decimal places you'll ever need to display? (Your examples have a max of 5).
If so, I would think that formatting with "0.#####" would do what you want.
static void Main(string[] args)
{
var dList = new decimal[] { 20, 20.00m, 20.5m, 20.5000m, 20.125m, 20.12500m, 0.000m };
foreach (var d in dList)
Console.WriteLine(d.ToString("0.#####"));
}
How to format a decimal without trailing zeros
There are several ways to do it, but since you are converting to a String object anyway, I suppose you could try something like this:
myDecimalVariable.ToString("G29");
or, using your code above, assuming 123.00M
is your decimal:
123.00M.ToString("G29");
Here is the explanation of how that concise example works:
The G format with a number means to format that many significant
digits. Because 29 is the most significant digits that a Decimal can
have, this will effectively truncate the trailing zeros without
rounding.
Remove trailing zeros
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation.
string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US")))
will give "1E-08" as the result.
Display decimal numbers without trailing zeros in an Access form
Go the solution Just go to property of the text box and changed the Format to General Number and Decimal Places to Auto
Format a decimal to remove trailing zeros and have a thousandths separator
The first thing to note is that you cant format strings as numbers correctly, they have to be numeric types. You can use double.TryParse
/ double.Parse
to make numeric types from a string if need be.
But the format you're looking for is #,000.##
var value1 = 1234.00;
var value2 = 1234.56;
var format = "#,###.##";
Console.WriteLine(value1.ToString(format)); // 1,234
Console.WriteLine(value2.ToString(format)); //1,234.56
Live example: https://dotnetfiddle.net/YoYcP0
Full details of custom numeric format strings and standard numeric format strings
Remove trailing zeros from decimal in SQL Server
A decimal(9,6)
stores 6 digits on the right side of the comma. Whether to display trailing zeroes or not is a formatting decision, usually implemented on the client side.
But since SSMS formats float
without trailing zeros, you can remove trailing zeroes by casting the decimal
to a float
:
select
cast(123.4567 as DECIMAL(9,6))
, cast(cast(123.4567 as DECIMAL(9,6)) as float)
prints:
123.456700 123,4567
(My decimal separator is a comma, yet SSMS formats decimal with a dot. Apparently a known issue.)
Removing any trailing zeros from a decimal in C#
I have found a solution. If the decimal (when converted to a string) has a decimal point in it a while loop keeps removing the last character all the time the last character is a 0.
string number = Convert.ToString(MyDouble);
if (number.Contains("."))
{
while(number.Substring(number.Length - 1) == "0")
{
number = number.Substring(0, number.Length - 1);
}
}
result = Convert.ToDecimal(number);
Avoid trailing zeroes in printf()
This can't be done with the normal printf
format specifiers. The closest you could get would be:
printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
but the ".6" is the total numeric width so
printf("%.6g", 3.01357); // 3.01357
breaks it.
What you can do is to sprintf("%.20g")
the number to a string buffer then manipulate the string to only have N characters past the decimal point.
Assuming your number is in the variable num, the following function will remove all but the first N
decimals, then strip off the trailing zeros (and decimal point if they were all zeros).
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
If you're not happy with the truncation aspect (which would turn 0.12399
into 0.123
rather than rounding it to 0.124
), you can actually use the rounding facilities already provided by printf
. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:
#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
The whole point of nDecimals()
in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness main()
shows this in action:
40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
Once you have the correctly rounded value, you can once again pass that to morphNumericString()
to remove trailing zeros by simply changing:
nDecimals (str, num[i], 3);
into:
nDecimals (str, num[i], 3);
morphNumericString (str, 3);
(or calling morphNumericString
at the end of nDecimals
but, in that case, I'd probably just combine the two into one function), and you end up with:
40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
Display decimal without trailing zeros in MVC view
Since your QuantityKg
is decimal?
instead of decimal
, you can use it's Value
property and use "N"
format specifier with 3
precision.
If everything is okey other than this, this should work in your case;
<td>@item.QuantityKg.Value.ToString("N3")</td>
But this throws InvalidOperationException
if QuantityKg
is null
, so using string.Format
would be better to catch this situation which generates empty string if it is null
as Panagiotis mentioned.
<td>@string.Format("{0:N3}", item.QuantityKg)</td>
Remove insignificant trailing zeros from a number?
If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.
var n = 1.245000
var noZeroes = n.toString() // "1.245"
Related Topics
How to Get the Child Windows of a Window Given Its Hwnd
How to Seed in Entity Framework Core 2
Linq to Entities, Random Order
Retrieving Creation Date of File (Ftp)
C# Naming Convention for Constants
How to Find a Specific Element in a List<T>
Setting/Getting the Class Properties by String Name
Connect to Network Drive with User Name and Password
How Best to Read a File into List<String>
Value Cannot Be Null. Parameter Name: Source
Using the Null-Conditional Operator on the Left-Hand Side of an Assignment
Why Are C# 4 Optional Parameters Defined on Interface Not Enforced on Implementing Class
What Is the Correct Performance Counter to Get CPU and Memory Usage of a Process