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

0

I need to transform the result from a value of As Double to the Brazilian numeric standard that uses a comma instead of a dot (and also keep 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
    
asked by anonymous 25.01.2018 / 16:59

2 answers

1

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

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

See working in .NET Fiddle     

25.01.2018 / 17:06
1

A Double value is just a number, it has no formatting, you can only convert it to String by applying formatting. This format should use a culture, in the Brazilian case.

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

See running on .NET Fiddle . And in the Coding Ground . Also put it in GitHub for future reference .

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

    
25.01.2018 / 17:13