Files
radzen-blazor/RadzenBlazorDemos/Models/Temperature.cs
Josh 2f17f0d4ae Support for IFormattable (#1318)
* Support IFormattable, if TValue implements it

* Include demo for custom numeric types

* improve method name

* In cases where the value is already of the correct type, do not perform conversion.  Refactor SetParametersAsync to honor custom numeric support

* perform the Min/Max check before the equality shortcut

* remove unnecessary type conversion logic

* fixup: if type implements IComparable, be sure to return value immediately, if in range

* PR feedback: this resolves the issue, in that the value is pushed to the dom via JS.  I couldn't understand why this existing statement had the other conditionals.  Why would you want to trigger the ValueChanged/Changed callbacks, if the value indeed hasn't changed, or if there's a Format.  However, admittedly I don't know the background of why it was this way.

https://github.com/radzenhq/radzen-blazor/pull/1318#issuecomment-1886478912

---------

Co-authored-by: Josh H <josh@inventivecoders.com>
2024-01-12 11:13:16 +02:00

35 lines
1.1 KiB
C#

using System;
using System.Globalization;
namespace RadzenBlazorDemos;
public record struct Temperature(decimal DegreesCelsius)
: IFormattable
{
public decimal Celsius => DegreesCelsius;
public decimal Fahrenheit => DegreesCelsius * 9 / 5 + 32;
public decimal Kelvin => DegreesCelsius + 273.15m;
public override string ToString() => ToString("G");
public string ToString(string format) => ToString(format, CultureInfo.CurrentCulture);
public string ToString(string format, IFormatProvider provider)
{
provider ??= CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
switch (format.ToUpperInvariant())
{
case "G":
case "C":
return $"{Celsius.ToString("F2", provider)} °C";
case "F":
return $"{Fahrenheit.ToString("F2", provider)} °F";
case "K":
return $"{Kelvin.ToString("F2", provider)} K";
default:
throw new FormatException($"The {format} format string is not supported.");
}
}
}