Formattazione di dati numerici per una lingua specifica

La classe NumberFormatInfo definisce la modalità di formattazione e visualizzazione della valuta, dei separatori decimali e di altri simboli numerici in base alla lingua. Il numero decimale 10000.50, ad esempio, viene formattato come 10,000.50 per la lingua "en-US" e come 10.000,50 per la lingua "de-DE".

È possibile creare un'istanza di NumberFormatInfo per una lingua specifica o per la lingua inglese, ma non per una lingua non associata ad alcun paese. Una lingua non associata ad alcun paese non fornisce informazioni sufficienti per visualizzare il formato numerico corretto. Se si cerca di creare un'istanza di NumberFormatInfo utilizzando una lingua non associata ad alcun paese, viene generata un'eccezione.

Nell'esempio di codice seguente viene visualizzato un valore integer utilizzando il formato di valuta standard NumberFormatInfo ("c") per il CurrentCulture specificato.

Imports System
Imports System.Globalization

Public Class TestClass

   Public Shared Sub Main()
      Dim i As Integer = 100
      
      ' Creates a CultureInfo for English in Belize.
      Dim bz As New CultureInfo("en-BZ")
      ' Displays i formatted as currency for the bz.
      Console.WriteLine(i.ToString("c", bz))
      
      ' Creates a CultureInfo for English in the U.S.
      Dim us As New CultureInfo("en-US")
      ' Displays i formatted as currency for us.
      Console.WriteLine(i.ToString("c", us))
      
      ' Creates a CultureInfo for Danish in Denmark.
      Dim dk As New CultureInfo("da-DK")
      ' Displays i formatted as currency for dk.
      Console.WriteLine(i.ToString("c", dk))
   End Sub
End Class
using System;
using System.Globalization;

public class TestClass
{
   public static void Main()
   {
      int i = 100;
      
      // Creates a CultureInfo for English in Belize.
      CultureInfo bz = new CultureInfo("en-BZ");
      // Displays i formatted as currency for the bz.
      Console.WriteLine(i.ToString("c", bz));
      
      // Creates a CultureInfo for English in the U.S.
      CultureInfo us = new CultureInfo("en-US");
      // Display i formatted as currency for us.
      Console.WriteLine(i.ToString("c", us));
      
      // Creates a CultureInfo for Danish in Denmark.
      CultureInfo dk = new CultureInfo("da-DK");
      // Displays i formatted as currency for dk.
      Console.WriteLine(i.ToString("c", dk));
   }
}

L'output del codice è il seguente:

BZ$100.00
$100.00
kr100,00

Formattazione della valuta per i paesi dell'euro

Entrambe le classi CultureInfo e RegionInfo includono informazioni sulla valuta. Viene specificata una sola valuta per lingua. L'euro è la valuta ufficiale di Belgio, Germania, Spagna, Francia, Irlanda, Italia, Lussemburgo, Paesi Bassi, Austria, Portogallo, Finlandia e Grecia. Il 1 gennaio 2002 questi paesi hanno iniziato a utilizzare banconote e monete in euro. Per questi dodici paesi che utilizzano l'euro come valuta ufficiale, in .NET Framework e Microsoft Windows XP il simbolo di valuta predefinito viene quindi impostato sull'euro. Nelle versioni precedenti di Windows, il simbolo di valuta predefinito verrà ancora impostato sul simbolo della valuta locale di questi paesi.

È necessario tenere in considerazione le differenze tra i sistemi operativi per quanto riguarda i simboli di valuta predefiniti. In Windows gli utenti sono in grado di eseguire l'override di alcuni valori associati alla lingua predefinita di sistema tramite Opzioni internazionali e della lingua o Impostazioni internazionali nel Pannello di controllo. Un utente, ad esempio, può scegliere di visualizzare la valuta utilizzando un simbolo diverso da quello predefinito per la lingua. In Windows Form e nelle applicazioni console viene utilizzato il simbolo di valuta predefinito specificato nel sistema dell'utente. Un utente che risiede in un paese che adotta l'euro e utilizza una versione precedente di Windows in cui l'impostazione della valuta sull'euro non è stata aggiornata tramite Impostazioni internazionali nel Pannello di controllo disporrà di un'impostazione di valuta predefinita non corretta. Le applicazioni ASP.NET e le applicazioni di servizi Web XML create in ASP.NET vengono eseguite come servizi di sistema, non per utenti specifici. I risultati predefiniti restituiti possono quindi differire da quelli restituiti da Windows Form e dalle applicazioni console.

È consigliabile scrivere codice che utilizza le impostazioni di valuta predefinite di .NET Framework per una lingua in modo da proteggere l'applicazione dalle differenze esistenti nei sistemi operativi e garantire una formattazione della valuta uniforme. Creare un oggetto CultureInfo utilizzando uno degli overload del costruttore che accetta un parametro useUserOverride e impostare tale parametro su false. In questo modo verrà eseguito l'override dell'impostazione di valuta predefinita nel sistema dell'utente con l'impostazione predefinita corretta di .NET Framework.

Nel seguente codice dei servizi Web XML il metodo dei servizi Web XML UserLocalSetting imposta CurrentCulture su "fr-FR" e restituisce un valore integer formattato come valuta. A causa delle differenze tra i sistemi operativi, non è possibile essere certi se verrà utilizzato il simbolo dell'euro o il simbolo "F". Il metodo del server Web XML OverrideUserSetting imposta CurrentCulture su "fr-FR" utilizzando il costruttore CultureInfo che accetta un parametro useUserOverride e imposta questo parametro su false. Viene restituito un valore integer formattato come valuta. Viene garantito l'uso del simbolo dell'euro in quanto è il valore predefinito di .NET Framework.

<%@ WebService Language="VB" Class="userOverrideSample" %>

Imports System
Imports System.Web.Services
Imports System.Globalization
Imports System.Threading

Public Class userOverrideSample

   <WebMethod> _
   Public Function UserLocalSetting() As String
      Dim i As Integer = 100

      ' Sets the CurrentCulture to French in France.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR")
      ' Displays i formatted as currency for the CurrentCulture.
      ' Due to operating system differences, you cannot be sure what currency
      ' symbol will be used.
      return (i.ToString("c"))
   End Function

   <WebMethod> _
   Public Function OverrideUserSetting() As String
      Dim i As Integer = 100

      ' Sets the CurrentCulture to French in France.
      ' Uses the CultureInfo constructor that takes a 
      ' useUserOverride parameter.
      ' Sets the useUserOverride value to false.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR", _
         false)
      ' Displays i formatted as currency for the CurrentCulture.
      ' This will override any user settings and display the euro symbol.
      return (i.ToString("c"))
   End Function 
End Class
<%@ WebService Language="c#" Class="userOverrideSample" %>

using System;
using System.Web.Services;
using System.Globalization;
using System.Threading;

public class userOverrideSample
{
   [WebMethod]
   public String UserLocalSetting()
   {
      int i = 100;

      // Sets the CurrentCulture to French in France.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
      // Displays i formatted as currency for the CurrentCulture.
      // Due to operating system differences, you cannot be sure what currency
      // symbol will be used.
      return (i.ToString("c"));
   }   
   
   [WebMethod]
   public String OverrideUserSetting()
   {
      int i = 100;

      // Sets the CurrentCulture to French in France.
      // Uses the CultureInfo constructor that takes a 
      // useUserOverride parameter.
      // Sets the useUserOverride value to false.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", _
         false);
      // Displays i formatted as currency for the CurrentCulture.
      // This will override any user settings and display the euro symbol.
      return (i.ToString("c"));
   }
}

Windows Form e le applicazioni console in esecuzione su tutte le versioni dei sistemi operativi Windows impostano il simbolo di valuta predefinito in base alle impostazioni nel computer dell'utente. Come è stato precisato in precedenza, questa impostazione potrebbe non essere corretta. Se si desidera garantire che l'applicazione utilizzi le impostazioni predefinite di .NET Framework, è necessario creare un oggetto CultureInfo passando un parametro useUserOverride impostato su false.

Nell'esempio seguente viene utilizzato codice simile all'esempio precedente. La lingua corrente viene impostata su "fr-FR" e viene visualizzato un valore integer sulla console formattato come valuta. Le impostazioni sulla valuta locale dell'utente vengono utilizzate per formattare la valuta. In seguito la lingua viene impostata su "fr-FR" tramite il costruttore CultureInfo che accetta il parametro useUserOverride impostato su false. Il numero viene quindi formattato utilizzando le impostazioni predefinite di .NET Framework e viene visualizzato il simbolo di valuta dell'euro.

Imports System
Imports System.Globalization
Imports System.Threading

Public Class EuroSymbolSample
   Public Shared Sub Main()
      Dim i As Integer = 100
      
      ' Sets the CurrentCulture to French in France.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR")
      ' Displays i formatted as currency for the CurrentCulture.
      ' On a version of Windows prior to Windows XP, where the user
      ' has not changed the default currency to euro through the
      ' Control Panel, this will default to "F".
      Console.WriteLine(i.ToString("c"))
      
      
      ' Sets the CurrentCulture to French in France, using the
      ' CultureInfo constructor that takes a useUserOverride parameter.
      ' Sets the useUserOverride value to false. 
      Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR", _ 
         False)
      ' Displays i formatted as default currency for the CurrentCulture.
      ' On a version of Windows prior to Windows XP, this will override an
      ' incorrect default setting of "F" and display the euro symbol ().
      Console.WriteLine(i.ToString("c"))
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class EuroSymbolSample
{
   public static void Main()
   {
      int i = 100;

      // Sets the CurrentCulture to French in France.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
      // Displays i formatted as default currency for the CurrentCulture.
      // On a version of Windows prior to Windows XP, where the user
      // has not changed the default currency to euro through the
      // Control Panel, this will default to "F".
      Console.WriteLine(i.ToString("c"));

      // Sets the CurrentCulture to French in France, using the
      // CultureInfo constructor that takes a useUserOverride parameter.
      // Sets the useUserOverride value to false. 
      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", 
            false);
      // Displays i formatted as default currency for the CurrentCulture.
      // On a version of Windows prior to Windows XP, this will override an
      // incorrect default setting of "F" and display the euro symbol ().
      Console.WriteLine(i.ToString("c"));      
   }
} 

Si noti che l'ambiente console non supporta il carattere dell'euro. Se si esegue questo codice in un'applicazione Windows Form, l'output avrà il seguente aspetto:

100,00 F
100,00 €

In molti paesi europei verranno utilizzate contemporaneamente due valute: l'euro e la valuta locale. È possibile che si verifichino casi in cui è necessario visualizzare entrambe le valute in un'applicazione. Nell'esempio di codice seguente viene creato un oggetto CultureInfo per la lingua "fr-FR" in cui la valuta predefinita è l'euro. Per visualizzare il simbolo di valuta corrispondente alla valuta locale, è necessario utilizzare il metodo NumberFormatInfo.Clone per clonare un nuovo NumberFormatInfo per CultureInfo e sostituire il simbolo di valuta predefinito con il simbolo della valuta locale.

Imports System
Imports System.Globalization
Imports System.Threading

Public Class EuroLocalSample
   Public Shared Sub Main()
      ' Creates a CultureInfo for French in France.
      Dim FrCulture As New CultureInfo("fr-FR")
      ' Sets the CurrentCulture to fr-FR.
      Thread.CurrentThread.CurrentCulture = FrCulture
      
      ' Clones the NumberFormatInfo and creates
      ' a new object for the local currency of France.
      Dim LocalFormat As NumberFormatInfo =_
         CType(NumberFormatInfo.CurrentInfo.Clone(), NumberFormatInfo)
      ' Replaces the default currency symbol 
      ' with the local currency symbol.
      LocalFormat.CurrencySymbol = "F"
      
      Dim i As Integer = 100
      ' Displays i formatted as the local currency.
      Console.WriteLine(i.ToString("c", LocalFormat))
      
      ' Displays i formatted as the default currency.
      Console.WriteLine(i.ToString("c", NumberFormatInfo.CurrentInfo))
   End Sub
End Class 
using System;
using System.Globalization;
using System.Threading;

public class EuroLocalSample
{
   public static void Main()
   {             
      // Creates a CultureInfo for French in France.
      CultureInfo FrCulture = new CultureInfo("fr-FR");
      // Sets the CurrentCulture to fr-FR.
      Thread.CurrentThread.CurrentCulture = FrCulture;

      // Clones the NumberFormatInfo and creates
      // a new object for the local currency of France.
      NumberFormatInfo LocalFormat = 
         (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
      // Replaces the default currency symbol with the 
      // local currency symbol.
      LocalFormat.CurrencySymbol = "F";

      int i = 100;

      // Displays i formatted as the local currency.
      Console.WriteLine(i.ToString("c", LocalFormat));

      // Displays i formatted as the default currency.
      Console.WriteLine(i.ToString("c", NumberFormatInfo.CurrentInfo));
   }
}

Per un esempio correlato, vedere l'esempio MultiCurrency in Guide rapide sulle attività comuni.

Vedere anche

Concetti

Formattazione per lingue differenti

Altre risorse

Codifica e localizzazione
Formattazione dei tipi di dati