Utilisation de Ssortingng Format pour afficher un nombre décimal inférieur ou égal à 2 ou un entier simple

J’ai un champ de prix à afficher qui peut parfois être 100 ou 100,99 ou 100,9. afficher 100 pas 100.00 et si le prix est 100.2, il devrait afficher 100.20 de même pour 100.22 devrait être le même. J’ai googlé et rencontré quelques exemples mais ils ne correspondaient pas exactement à ce que je voulais:

// just two decimal places Ssortingng.Format("{0:0.00}", 123.4567); // "123.46" Ssortingng.Format("{0:0.00}", 123.4); // "123.40" Ssortingng.Format("{0:0.00}", 123.0); // "123.00" 

Une manière inélégante serait:

 var my = DoFormat(123.0); 

Avec DoFormat quelque chose comme:

 public static ssortingng DoFormat( double myNumber ) { var s = ssortingng.Format("{0:0.00}", myNumber); if ( s.EndsWith("00") ) { return ((int)myNumber).ToSsortingng(); } else { return s; } } 

Pas élégant mais travaillant pour moi dans des situations similaires dans certains projets.

Désolé d’avoir réactivé cette question, mais je n’ai pas trouvé la bonne réponse ici.

En formatant les nombres, vous pouvez utiliser 0 comme lieu obligatoire et # comme emplacement facultatif.

Alors:

 // just two decimal places Ssortingng.Format("{0:0.##}", 123.4567); // "123.46" Ssortingng.Format("{0:0.##}", 123.4); // "123.4" Ssortingng.Format("{0:0.##}", 123.0); // "123" 

Vous pouvez également combiner 0 avec # .

 Ssortingng.Format("{0:0.0#}", 123.4567) // "123.46" Ssortingng.Format("{0:0.0#}", 123.4) // "123.4" Ssortingng.Format("{0:0.0#}", 123.0) // "123.0" 

Pour cette méthode de formage est toujours utilisé CurrentCulture . Pour certaines cultures . sera changé pour,.

Ceci est un cas d’utilisation courant de nombre flottant de formatage.

Malheureusement, toutes les chaînes de format à une lettre intégrées (par exemple, F, G, N) ne parviendront pas directement à cela.
Par exemple, num.ToSsortingng("F2") affichera toujours 2 décimales comme 123.40 .

Vous devrez utiliser le modèle 0.## même s’il est un peu verbeux.

Un exemple de code complet:

 double a = 123.4567; double b = 123.40; double c = 123.00; ssortingng sa = a.ToSsortingng("0.##"); // 123.46 ssortingng sb = b.ToSsortingng("0.##"); // 123.4 ssortingng sc = c.ToSsortingng("0.##"); // 123 

essayer

 double myPrice = 123.0; Ssortingng.Format(((Math.Round(myPrice) == myPrice) ? "{0:0}" : "{0:0.00}"), myPrice); 

Ancienne question mais je voulais append l’option la plus simple à mon avis.

Sans milliers de séparateurs:

 value.ToSsortingng(value % 1 == 0 ? "F0" : "F2") 

Avec des milliers de séparateurs:

 value.ToSsortingng(value % 1 == 0 ? "N0" : "N2") 

La même chose mais avec Ssortingng.Format :

 Ssortingng.Format(value % 1 == 0 ? "{0:F0}" : "{0:F2}", value) // Without thousands separators Ssortingng.Format(value % 1 == 0 ? "{0:N0}" : "{0:N2}", value) // With thousands separators 

Si vous en avez besoin à plusieurs endroits , j’utiliserais cette logique dans une méthode d’extension :

 public static ssortingng ToCoolSsortingng(this decimal value) { return value.ToSsortingng(value % 1 == 0 ? "N0" : "N2"); // Or F0/F2 ;) } 

Je ne sais de toute façon pas mettre une condition dans le spécificateur de format, mais vous pouvez écrire votre propre formateur:

 using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(ssortingng[] args) { // all of these don't work Console.WriteLine("{0:C}", 10); Console.WriteLine("{0:00.0}", 10); Console.WriteLine("{0:0}", 10); Console.WriteLine("{0:0.00}", 10); Console.WriteLine("{0:0}", 10.0); Console.WriteLine("{0:0}", 10.1); Console.WriteLine("{0:0.00}", 10.1); // works Console.WriteLine(Ssortingng.Format(new MyFormatter(),"{0:custom}", 9)); Console.WriteLine(Ssortingng.Format(new MyFormatter(),"{0:custom}", 9.1)); Console.ReadKey(); } } class MyFormatter : IFormatProvider, ICustomFormatter { public ssortingng Format(ssortingng format, object arg, IFormatProvider formatProvider) { switch (format.ToUpper()) { case "CUSTOM": if (arg is short || arg is int || arg is long) return arg.ToSsortingng(); if (arg is Single || arg is Double) return Ssortingng.Format("{0:0.00}",arg); break; // Handle other default: try { return HandleOtherFormats(format, arg); } catch (FormatException e) { throw new FormatException(Ssortingng.Format("The format of '{0}' is invalid.", format), e); } } return arg.ToSsortingng(); // only as a last resort } private ssortingng HandleOtherFormats(ssortingng format, object arg) { if (arg is IFormattable) return ((IFormattable)arg).ToSsortingng(format, CultureInfo.CurrentCulture); if (arg != null) return arg.ToSsortingng(); return Ssortingng.Empty; } public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } } } 

Code de ligne simple:

 public static ssortingng DoFormat(double myNumber) { return ssortingng.Format("{0:0.00}", myNumber).Replace(".00",""); } 

Voici une alternative à la méthode de Uwe Keim, qui maintiendrait toujours le même appel de méthode:

 var example1 = MyCustomFormat(123.1); // Output: 123.10 var example2 = MyCustomFormat(123.95); // Output: 123.95 var example3 = MyCustomFormat(123); // Output: 123 

Avec MyCustomFormat quelque chose comme:

 public static ssortingng MyCustomFormat( double myNumber ) { var str (ssortingng.Format("{0:0.00}", myNumber)) return (str.EndsWith(".00") ? str.Subssortingng(0, strLastIndexOf(".00")) : str; } 

Je crains qu’il n’y ait pas de format intégré pour le faire. Vous devrez utiliser un format différent selon que la valeur est un nombre entier ou non. Ou formatez toujours à 2 décimales et manipulez ensuite la chaîne pour supprimer tout “.00” final.

Si aucune des autres réponses ne fonctionne pour vous, cela peut être dû au fait que vous ContentProperty d’un contrôle dans la fonction OnLoad , ce qui signifie que cela ne fonctionnera pas:

 private void UserControl_Load(object sender, RoutedEventArgs e) { Bind.SetBindingElement(labelName, Ssortingng.Format("{0:0.00}", PropertyName), Label.ContentProperty) } 

La solution est simple: il existe une propriété ContentSsortingngFormat dans xaml. Donc, lorsque vous créez l’étiquette, faites ceci:

 //if you want the decimal places definite  

Ou

 //if you want the decimal places to be optional  

quelque chose comme ça fonctionnera aussi:

 Ssortingng.Format("{0:P}", decimal.Parse(Resellers.Fee)).Replace(".00", "") 

Ssortingng.Format (“{0: 0.00}”, Convert.ToDecimal (totalPrice))

Pour que le code soit plus clair dans ce que Kahia a écrit (c’est clair mais ça devient compliqué quand on veut y append du texte) … essayez cette solution simple.

 if (Math.Round((decimal)user.CurrentPoints) == user.CurrentPoints) ViewBag.MyCurrentPoints = Ssortingng.Format("Your current Points: {0:0}",user.CurrentPoints); else ViewBag.MyCurrentPoints = Ssortingng.Format("Your current Points: {0:0.0}",user.CurrentPoints); 

J’ai dû append la dissortingbution supplémentaire (décimale) pour que Math.Round compare les deux variables décimales.

Si votre programme doit s’exécuter rapidement, appelez value.ToSsortingng (formatSsortingng) pour obtenir des performances de formatage des chaînes ~ 35% plus rapides que $ “{value: formatSsortingng}” et ssortingng.Format (formatSsortingng, value).

Les données

Performances de mise en forme de chaîne C # - VS2017 15.4.5

Code

 using System; using System.Diagnostics; public static class SsortingngFormattingPerformance { public static void Main() { Console.WriteLine("C# Ssortingng Formatting Performance"); Console.WriteLine("Milliseconds Per 1 Million Iterations - Best Of 5"); long ssortingngInterpolationBestOf5 = Measure1MillionIterationsBestOf5( (double randomDouble) => { return $"{randomDouble:0.##}"; }); long ssortingngDotFormatBestOf5 = Measure1MillionIterationsBestOf5( (double randomDouble) => { return ssortingng.Format("{0:0.##}", randomDouble); }); long valueDotToSsortingngBestOf5 = Measure1MillionIterationsBestOf5( (double randomDouble) => { return randomDouble.ToSsortingng("0.##"); }); Console.WriteLine( $@" $""{{value:formatSsortingng}}"": {ssortingngInterpolationBestOf5} ms ssortingng.Format(formatSsortingng, value): {ssortingngDotFormatBestOf5} ms value.ToSsortingng(formatSsortingng): {valueDotToSsortingngBestOf5} ms"); } private static long Measure1MillionIterationsBestOf5( Func formatDoubleUpToTwoDecimalPlaces) { long elapsedMillisecondsBestOf5 = long.MaxValue; for (int perfRunIndex = 0; perfRunIndex < 5; ++perfRunIndex) { var random = new Random(); var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < 1000000; ++i) { double randomDouble = random.NextDouble(); formatDoubleUpToTwoDecimalPlaces(randomDouble); } stopwatch.Stop(); elapsedMillisecondsBestOf5 = Math.Min( elapsedMillisecondsBestOf5, stopwatch.ElapsedMilliseconds); } return elapsedMillisecondsBestOf5; } } 

Sortie de code

 C# Ssortingng Formatting Performance Milliseconds Per 1 Million Iterations - Best Of 5 $"{value:formatSsortingng}": 419 ms ssortingng.Format(formatSsortingng, value): 419 ms value.ToSsortingng(formatSsortingng): 264 ms 

Les références

Chaînes de format numérique personnalisées [docs.microsoft.com]

Qt Charts Exemple de BarChart [doc.qt.io]

Cela a fonctionné pour moi!

 Ssortingng amount= "123.0000"; Ssortingng.Format("{0:0.##}", amount); // "123.00"