Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number to currency using VB.Net

I got for you today a simple problem that already took me part of the day with no real achievement. I'm trying to format a number to display as a currency. There's many ways to do that, I think I've done most of 'em.

So here's the problem: I'm adding multiple number which can be positive and negative, I can't know. When I'm formatting at the end using TextBox.Text = Format(variable, "C"), I got the right format for positive numbers (which is per example 123 456,00 $, I live in Canada) and I have (123 456,00 $) for negative ones. I would prefer to have the "-" symbol at the beginning.

I searched the web to find other ways to do that, per example : FormatCurrency("-123 456", 2, TriState.True, TriState.False). That way I'm able to get rid of the parentheses but the "-" is AFTER the number (123 456,00 $-).

Next one: SpecificCulture. so here I have NegativeValueHere.ToString("C", CultureInfo.CreateSpecificCulture("fr-CA")) . With that I'm back at the beginning with my parentheses with (123 456,00 $). Note here that my application is running with culture set to ("fr-CA") since that's where I live.

I tried one more but can't remember what it was.However the "$" was in front of the number like $-123 456,00.

Note: I'm running on VB.Net, and the number has to be formatted to be put in a readonly TextBox.

like image 592
Simon Avatar asked Feb 13 '26 00:02

Simon


1 Answers

You can create your own culture with a custom pattern for negative currency values. Take a look at the MSDN library article for NumberFormatInfo.CurrencyNegativePattern. For example:

Imports System.Globalization

Module Module1
    Sub Main()
        Dim simon = DirectCast(CultureInfo.GetCultureInfo("fr-CA").Clone, CultureInfo)
        simon.NumberFormat.CurrencyNegativePattern = 1
        Dim test = -1234.567
        Console.WriteLine(test.ToString("C", simon))
        Console.ReadLine()
    End Sub
End Module

Output: -$1 234,57

like image 174
Hans Passant Avatar answered Feb 15 '26 18:02

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!