I need to format a floating point number to x characters (6 in my case including the decimal point). My output also needs to include the sign of the number
So given the inputs, here are the expected outputs
1.23456 => +1.2345
-12.34567 => -12.345
-0.123456 => -0.1234
1234.567 => +1234.5
Please assume there is always a decimal place before the last character. I.e. there will be no 12345.6
number input - the input will always be less than or equal to 9999.9
.
I'm thinking this has to be done conditionally.
You mention "x characters". So we can simplify that to "x-1 digits", and just write code that shows x digits.
I think passing the "G" numeric format specifier to Double.ToString()
is as close to built-in as you can get.
double d = 1234.56789;
string s = d.ToString("G6"); // "1234.57"
So we just expand that to manually add the "+" at the front:
if (d > 0)
s = "+" + s;
Putting it all together in an extension method:
EDIT: Includes optional parameter to truncate
public static string ToStringWithSign(this double d, int digits, bool truncate = false)
{
if (truncate) {
double factor = Math.Pow(10, digits - 1);
d = Math.Truncate(d * factor) / factor;
}
string s = d.ToString("G" + digits);
if (d > 0)
s = "+" + s;
return s;
}
Results:
(1234.56789).ToStringWithSign(4); // "+1235"
(1234.56789).ToStringWithSign(5); // "+1234.6"
(1234.56789).ToStringWithSign(6); // "+1234.57"
(-1234.56789).ToStringWithSign(6); // "-1234.57"
(1.2345678).ToStringWithSign(6); // "+1.23457"
(1.2345678).ToStringWithSign(6, true); // "+1.23456"
If you want truncation:
string str = number.ToString("+0.00000;-0.00000").Substring(0,7);
If you want rounding:
string str = number.ToString("+0.0000;-0.0000");
EDIT: if you want, you can write a simple wrapper that takes the number of digits as a parameter:
string FormatDecimal(decimal value, int digits )
{
return value
.ToString(String.Format("+0.{0};-0.{0}", new string('0',digits - 2)))
.Substring(0,digits+1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With