Convert the string "5.541.00" to int in C#

Asked

Viewed 229 times

1

What is the correct way to convert a string with the text "5.541,88" to int?

I’m trying to do it this way:

int valor = int.Parse("5.541,88");

But I can’t because it returns the error:

Input string was not in a correct format.

  • Use Convert.Toint32()

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

3 answers

7

The right shape is using the style of value and the culture it is to be able to identify the pattern.

And of course, check if it worked before using, because it might fail (TryParse()), I will not let the application break down, nor use an exception for a not exceptional situation, it seems to be expected that the data will come to failures. If it is guaranteed that the data will not come with formatting flaws, then you can use the Parse() and without exception.

I’ll use decimal because clearly this is a monetary value, it doesn’t make much sense to try to take the whole value of it, but if you want to do it then just make sure that you want to lose part of the value, this is not part of the conversion itself.

If you really want to convert to whole you can make an explicit conversion (it’s better than a cast because it makes clear the desired semantics and is most likely to catch the best approximation - ToInt32()).

But if you really want to throw away the pennies, then truncate the value (Truncate()).

But if it’s monetary value and you only want to have the whole part then you should keep the type using the Truncate() of the kind decimal.

I made all options in:

using static System.Console;
using static System.Convert;
using static System.Math;
using System.Globalization;

public class Program {
    public static void Main() {
        if (!decimal.TryParse("5.541,88", NumberStyles.Currency, CultureInfo.CreateSpecificCulture("pt-BR"), out var valor)) WriteLine("Formato inválido para conversão");
        WriteLine($"Decimal: {valor}");
        WriteLine($"Inteiro: {ToInt32(valor)}");
        WriteLine($"Inteiro truncado: {Truncate(valor)}");
        WriteLine($"Decimal truncado: {decimal.Truncate(valor)}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • 6

    Anyone who was negative could say what was wrong with the answer. If you’re wrong, it’s important for the community to demonstrate that people don’t learn wrong. I can’t see a single mistake, I asked other people who understand and didn’t see it either, so it just seems like an unconformized group vote for something.

  • I checked, I guess I hadn’t added the using static System.Console; at the time I ran your code. Now it’s 100% after I added it worked.

-4

Conversion is not working because it does not detect the value format, so try:

  string ii = "5541.88";
        float value = float.Parse(ii, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
  • 1

    You know this does not result in what he wants, has conceptual problem and breaks the application if the data is coming from unreliable source?

  • Your string ii is not the same as what the guy posted, if it were so would be a much more direct conversion.

  • I simply answered the question "Convert the String "5,541.00" to Int in C#" with a simple adjustment that the variable cannot integer(possible error in question), what is my mistake here? the objective is not to have the variable value with the value "5541.88"???

  • There is no error in the question, including the two answers given treat this case.

-6

One way to solve is to use decimal.parse and then cast to integer value.

Follow an example:

using System;
using System.Globalization;

public class TransformToIntegerRepresentation
{
    public static void Main()
    {
        string valor = "5.541,88";
        NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
        CultureInfo provider = new CultureInfo("pt-BR");
    
        try {
            decimal numero = Decimal.Parse(valor, style, provider);
            Console.WriteLine("'{0}' convertido para {1}.", valor, (int) numero);
        } catch (FormatException) {
            Console.WriteLine("Não foi possível representar o valor em um inteiro válido");
        }
    }
}

In this example I am using utility classes to allow the thousand group separator and allow the decimal value separator. I also added a local culture promoter pt-BR. So we can cast a "formatted" decimal number to be represented in pt-BR.

Last time to display the value I force the decimal cast to int.

  • 5

    If the conversion fails gives error and breaks the application, it was the desired, right?

  • @Maniero thanks for reporting, already I will adjust with the Try catch.

  • 6

    If it is known that you can make a mistake, why capture an exception? Exceptions are for cases where the error should not occur, there is already a ready and correct way to do it performatively and semantically to deal with the failure case.

  • 2

    You had said that my code does not work on ideone, but I edited the answer to put demo that works on it yes, just like in . NET Fiddle. As you had negatively before could review now, or else inform which.

  • I didn’t check again, I see.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.