Reputation: 603
I have numbers like this: -1.0001 -10000.01
And I need to get this: -1.0001 -10000,01
Requirements: - Decimal separator is "," - Group separator is " " - part of a number after the comma can have different length, that depends from actual data.
I tried to use this mask: "### ### ##0.####" to format numbers. When number is big - all is ok, but when it is small - I get spaces from the left of a number. I get this: "- 1,0001" "- 10 000,01"
As I understand these spaces are from the mask I used.
There are some workaround ways but they are not so beautiful and aesthetically wright.
Is there any way to do this correctly?
Thank you!
Upvotes: 0
Views: 213
Reputation: 2194
Try using the NumberFormatInfo class to format your number. I used the code below to check my answer and it worked for the large/small cases I tested with:
static void Main(string[] args)
{
double smallNumber = -1.01;
double smallNumberMoreDigits = -1.0001;
double bigNumber = -100000.001;
double longNumber = 2.2347894612789;
Thread.CurrentThread.CurrentCulture = new CultureInfo("ru", false);
Console.Out.WriteLine(smallNumber.ToString("#,0.####"));
Console.Out.WriteLine(smallNumberMoreDigits.ToString("#,0.####"));
Console.Out.WriteLine(bigNumber.ToString("#,0.####"));
Console.Out.WriteLine(longNumber.ToString("#,0.####"));
Console.Read();
}
EDIT: A quick bit of detective work (I looked at your profile) tells me you're in Russia. Are you looking for the General Russian number formatting? I've changed the code above. Take a look and see if it fits your requirements. It gives me the following results:
-1,01 -1,0001 -100000,001
SECOND EDIT: Added masking to get a better result on decimal places.
Upvotes: 1
Reputation: 720
The spaces were automatically removed by stackoverflow when you posted but I think you can solve your problem by just using Trim like
something.ToString("### ### ##0.####").Trim();
Upvotes: 1