How to know how many characters there are after the comma c#

Asked

Viewed 710 times

-2

I would like to count how many characters there are after the comma. I was using

public static string strToDouble(String text)
        {
            string aux;
            if (text.IndexOf(",00") <= 0)
            {
                aux = text + ",00";

                return aux;
            }
            return text;
        }

But it only returns me if these characters are in the variable.

I need to know if it has a comma and if so how many characters.

  • 1

    What you want to do exactly with the method strToDouble()? Take a number and if there are no decimal places add two?

  • 4

    You need to clarify what you want, this method does one thing, you now want it to do something else? Or you want another method?

  • The idea of the method was to take the number if it had no decimal places and add yes.

  • But I would like a method to count and I can add in a different way

  • For example if the number is 1.5 it adds only a zero 1.50 if it is 1.06 it adds none if it is 1 it adds two zeros 1.00

  • 1

    Let’s better understand what you want. Your method has a name that seems to want to transform a text to a number of the type double?. Is that correct? it seems to be an XY problem, you want something else from what you’re asking. Say what you need to solve to give the most appropriate solution, it seems that what you are asking is not the solution to your problem. What is the data you have? It’s a string being read somewhere?

Show 1 more comment

2 answers

1


Try it like this:

//String alvo
string palavra = "3,5888666454";
//Pega onde está a virgula
int virgulaIndice = palavra.IndexOf(',');
//Divide e pega apenas os chars[] depois da virgula
string restoDepoisDaVirgula = palavra.Substring(virgulaIndice);
//Conta todos esses chars[]
int tamanhoDepoisDaVirgula = restoDepoisDaVirgula.Length;           
//Tem que tirar uma casa, pois é a casa da própria virgula, queremos apenas as casas depois dela
tamanhoDepoisDaVirgula--;

//Esta pronto, agora é só usar a var tamanhoDepoisDaVirgula para saber a quantidade!

-1

Break your string into an array with the split

var res = suaString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

The second position of the array will contain the part of the string after the comma

if (res.Count() > 1)
  var qrdt = res[1].Lenght;

Gabriel https://desenvolvimentofullstack.wordpress.com

Browser other questions tagged

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