I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format
, but it returns 2.0000
and setting it to N0
rounds the other values as well.
I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format
, but it returns 2.0000
and setting it to N0
rounds the other values as well.
try this code:
I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
Basically
decimal v=2.4200M;
v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.
Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?
If for display consider formatting the numbers are x.ToString("")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
If it is just rounding, use Math.Round overload that requires a MidPointRounding overload
http://msdn.microsoft.com/en-us/library/ms131274.aspx)
If you get your value from a database consider casting instead of conversion: double value = (decimal)myRecord["columnName"];
The following code could be used to not use the string type:
Returns 789.5
In my opinion its safer to use Custom Numeric Format Strings.
Truncate trailing Zeros is very easy, resolve with a duplex cast:
(I) --> Parse decimal value from any string source.
(II) --> First: Cast to double this remove the trailing zeros. Second: Other cast to decimal because dont exist implicit conversion from decimal to double and viceversa)