Correctly print a double value using Tostring()

Asked

Viewed 60 times

0

I’m having difficulty printing a monetary value correctly with the distribution of its decimal places, I used the ToString() using parameters such as "C", "F" and "N", what needs to be done to leave a correct monetary value?

using static System.Console;
using System.Globalization;

namespace AtividadeRepeticao
{
    class Program2
    {
        static int Main(string[] args)
        {
            double valor = 1000.50;
            Write($"Valor: {valor.ToString("C", CultureInfo.CurrentCulture)}");
            ReadKey();
            return 0;
        }
    }
}    
// Valor esperado
1.000,50
// Valor imprimido
100.050,00
  • You have a syntax error Write($"R$: {valor.ToString("C", CultureInfo.CurrentCulture}));, correct that there.

  • I corrected the syntax here and did not present this result suggested in the question: outworking

1 answer

2


If you want a monetary value you use a decimal and not a double. If you want in the current culture you have no reason to specify this.

using static System.Console;

namespace AtividadeRepeticao {
    class Program2 {
        static void Main() {
            decimal valor = 1000.50M;
            Write($"R$: {valor}");
        }
    }
}

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

I think this code produces a more suitable result, but if you want to insist on your way and the problem is quotation marks inside quotation marks then use parentheses:

using static System.Console;

namespace AtividadeRepeticao {
    class Program2 {
        static void Main() {
            decimal valor = 1000.50M;
            Write($"R$: {valor.ToString(("C"))}");
        }
    }
}

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

Browser other questions tagged

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