How to format a Double by swapping a semicolon and keeping 2 decimal places in VB.NET

Asked

Viewed 1,299 times

-1

I need to transform the result of a value of As Double for the Brazilian numerical standard that uses comma instead of dot (and also maintain only 2 decimal places), thus:

' variaveis de teste                       ' valores esperados de saida   
Dim t1 as double = 123                     ' ~> 123,00
Dim t2 as double = 123.123                 ' ~> 123,12
Dim t3 as double = 123123132112321321.123  ' ~> 123123132112321321,12
Dim t4 as double = 0.123                   ' ~> 0,12
Dim t4 as double = 0.158123                ' ~> 0,16

2 answers

2


The method ToString has an overload that accepts a CultureInfo as parameter. Pass this parameter using the culture you want.

Dim valor = 5.89d
valor.ToString(new CultureInfo("pt-br"))

See working on . NET Fiddle

  • That’s right! Thank you very much! I was already thinking about some crazy things like ToString().Replace() rs

1

A value Double is only a number, it has no formatting, it is only possible to turn it into String applying a formatting. This formatting should use a culture, in this case the Brazilian.

Imports System
Imports System.Globalization
                
Public Module Module1
    Public Sub Main()
        Dim ptbr = new CultureInfo("pt-br")
        Console.WriteLine("{0}", 123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 123.123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 123123132112321321.123d.ToString("N2", ptbr))
        Console.WriteLine("{0}", 0.123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 0.158123.ToString("N2", ptbr))
    End Sub
End Module

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

Just note that if this is money the Double is not the right kind.

  • yes @LINQ ended up passing the answer above, and the way he put it became simpler, even so thank you.

  • 1

    Although I don’t do exactly what you asked

  • actually does yes, what I need is to just exchange the point for comma and not format as money or currency =D

  • So your question was misspelled because it clearly shows that it needs to have only 2 decimal places in all cases.

  • I changed the question to make it clearer then

  • So mine is correct according to your question, and LINQ’s, despite the good intention, not: https://dotnetfiddle.net/qy7Ids

Show 1 more comment

Browser other questions tagged

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