Home > Net >  Format negative number C#
Format negative number C#

Time:07-05

I have a variable that when it is smaller that zero it formats the number to -5,650 allowing AllowThousands using comma as separator

however when I try to check the value it throws me an exception... what can I do?

if (int.Parse("-5,650", NumberStyles.AllowLeadingSign) < 0)

The exception string is the next:

System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, NumberStyles style) at Sistema_Caja_Temp_wpf.Vistas.RegistraVentas.btnPagarClick(Object sender, RoutedEventArgs e) in C:\Users\estem\OneDrive\Documents\PROYECTOS\Sistema Caja Temp wpf\Vistas\RegistraVentas.xaml.cs:line 210

CodePudding user response:

Besides going with the "nuclear" option of NumberStyles.Any, you can combine NumberStyles entries. Good news is that you already know which ones to use.

int.Parse("-5,650", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign);
// gives "-5650" as an Int32

CodePudding user response:

Change your number style to NumberStyles.Any and the code you posted succeeds.

CodePudding user response:

Integer is only for numbers without a decimal place. If you want to accept numbers with decimal places like in your example you should change your code to float, double or decimal

so if you change your Code to

if (float.Parse("-5,650") < 0)

it should work.

if you want to test if your input has the correct format you can use TryParse instead.

like this

int input;

if (int.TryParse("-5,650", out input) && input < 0)
  •  Tags:  
  • c#
  • Related