0

Is there a way to ensure that 'relevant to human visual display' information, particularly in context of interpolated $".." strings is preserved?

Use case:

double errors = 1.0 / 25000; // => 0.004
var errorMessage = $"Data had {errors:F2}% errors!";

However, the current output is a bit misleading, as it "reads as" '0%' errors.

Data had 0.00% errors.

What is a simple method in C# to achieve an output such as the following instead? (Naturally, there should be no 100.01%..)

Data had 0.01% errors.

The Math.Round function is not directly suitable without finagling, as the rounding applies to midpoint values, not to 'at precision'.

Math.Round(errors, 2, MidpointRounding.AwayFromZero) // => 0; desired is 0.01
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    I suppose that is a duplicate (thanks!), *however* the accepted answer seems inferior to to one of the other answers on the same question ( https://stackoverflow.com/a/7075236/2864740 ) (which starts with a decimal, that is base-10). – user2864740 Feb 23 '21 at 19:19
  • floating-point precision shenanigans are unavoidable if you use floating-point variables. The `decimal` type helps you avoid this. https://learn.microsoft.com/en-us/dotnet/api/system.decimal.ceiling?view=net-5.0 – Pranav Hosangadi Feb 23 '21 at 19:24
  • MidpointRounding.AwayFromZero Doesn't work because 0.004 is not a midpoint. Perhaps you want to `*100` and math.ceil the result? – Caius Jard Feb 23 '21 at 19:51
  • @CaiusJard Yup, that's what I was looking for as covered in the duplicate-question answers (with relevant details). I was hoping there was a built-in method for such relating to/around the string formatting (and there is not). – user2864740 Feb 23 '21 at 22:48

1 Answers1

0

I think the easiest solution would be to create your own function that rounds up. Using an if statement you could do something like: if errorMargin is bigger than 0.00 and smaller than 0.01, set errorMargin to 0.01

matttco4
  • 1
  • 1