C
C#8mo ago
digiholic

Format a Number to a String in Scientific Notation, Only if It Has Enough Digits

I have a series of numbers that can be either large integers, or very small decimals. I would like numbers with more than four digits to be displayed in scientific notation. At first, I considered a custom number format 0.000E+0, but that puts E+0 at the end of any numbers with less than four digits. While searching, I was suggested using the General formatter G4, but that doesn't turn small decimal numbers into Scientific Notation, for example, 0.001234 remains as 0.001234 instead of becoming 1.234E-3 as I would expect. I need a number format string that fulfills the following conditions:
0 -> 0
1234 -> 1234
12348 -> 1.235E3
0.123 -> 0.123
0.1234 -> 1.234E-1
0.001234 -> 1.234E-3
0 -> 0
1234 -> 1234
12348 -> 1.235E3
0.123 -> 0.123
0.1234 -> 1.234E-1
0.001234 -> 1.234E-3
3 Replies
Angius
Angius8mo ago
Humanizer might be able to do that?
digiholic
digiholic8mo ago
It needs to be specifically a format string, I'm passing it to a Blazor Component
Angius
Angius8mo ago
Edit the component to use Humanizer ¯\_(ツ)_/¯