How to convert text into file to number with decimals?

Asked

Viewed 200 times

1

I have this data written in the text file "000001010" (you only have this data), but I wanted when it was for the variable to be like this 10.10.

I’m reading the file data like this:

var linhas = System.IO.File.ReadAllLines(@"C:\teste\pedro.txt");
  • But what is the rule, young man? The last two will always be the decimal part?

  • @LINQ I will try to explain better, for example if it is 000000010 this corresponds to 0,10 if it is 000010000 this corresponds to 100 understood ?

  • This I already understood at the beginning. Anyway, you want these values as numeric or as string?

  • @NUMERICAL LINQ

2 answers

5


By the rule described: just convert the number to integer and divide by 100.

I took the opportunity to do with LINQ, so each line of the file will return an item to the list valores.

var valores = File.ReadAllLines(@"C:\teste\pedro.txt")
                  .Select(l => (decimal)Convert.ToInt32(l) / 100)
                  .ToList();

foreach(var val in valores)
    Console.WriteLine(val);

See working on . NET Fiddle.

Considering that each file will have only one line, it would be better to do so:

var strVal = File.ReadAllLines("C:\teste\pedro.txt")[0];
decimal valor = Convert.ToInt32(strVal) / 100m;    
  • Whereas each file will only have one line is not worth being a list or it really has to be a list ?

  • @Pedroazevedo No need. You can put a 0 after ToList if you want to continue using LINQ, otherwise I can give a better suggestion.

  • I’ll test this but I don’t need a list because the file always has only one line

  • @Pedroazevedo I added at the end of the answer an alternative =)

  • Thank you very much :D

1

Assume that the format is always this and will always be correct can do:

using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        var campo = "000001010";
        decimal valor = ToInt32(campo) / 100M;
        WriteLine(valor);
    }
}

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

If you have a unique element in the file just read it like this:

File.ReadAllLines("C:\teste\pedro.txt")[0];

As the method ReadAllLines() returns a array with all the lines of text in the file and only has one line just grab the first element. No need to make other manipulation because the line contains no other information.

Browser other questions tagged

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