-1

Hi I have the function:

public static string MapDiePitchY(string DiePitchY)
{
    
    float value = float.Parse(DiePitchY) * 1000;
    int valInt = (int)value;
    string temp = valInt.ToString();
    return temp;
}

When I run it with these two numbers, I get two different behaviours:

str = MapDiePitchY("4150.8");

Returns 4150799

While

str = MapDiePitchY("2767.3");

Returns 2767300 which is what I'd expect and want everytime I pass in a float

I want the function to always return the value multiplied by 1000 but with no rounding. I've tried to replace the 1000 with 1000f and still get the behaviour where it adds extra value to 4150.8. Values that shouldn't exist there. I have no idea why this is happenign and googling hasn't given me any answers.

Is there a way to ensure I get the exact value I pass in as string but multiplied by 1000 with no rounding?

I am on C# 7.3

devn00b1090
  • 97
  • 1
  • 8
  • 2
    Does this answer your question? [C# Maths gives wrong results!](https://stackoverflow.com/questions/5179452/c-sharp-maths-gives-wrong-results), [Is floating point math broken?](https://stackoverflow.com/q/588004/8967612) – 41686d6564 stands w. Palestine Jun 06 '22 at 22:53

1 Answers1

1

So you understand floating-point numbers are not exact. When you type float x = 4150.8f the internal bit representation of the number is

x = (1 + 112230 * 2^(-23)) * 2^(139-127) = 4150.7998046875

The integers m=112230 and e=139 represent the mantissa and exponent of the floating-point number.

The above is the result of the parse function. Then you multiply by 1000 which results in

value = x*1000 = 4150799.8046875

what you want to do at this point is do the rounding before converting into an integer

int valInt = (int)Math.Round(value);

which should round up the .80.. in the end into the next whole number 4150800.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133