locked
Problem when using Math.Round() ? RRS feed

  • Question

  • Hi everyone,

    I used Math.Round as below codes:

    float result = 0;
    result = (float)Math.Round(double.Parse(numberString),1);
    MessageBox.Show(result.ToString());

    After executing the above lines, the message content is: 1324.5999

    Are there any one know why and how to fix it ?

    Thanks and regards,

    Sunday, April 28, 2013 2:49 AM

Answers

  • You need to change how you display the floating point value:

    MessageBox.Show(result.ToString("F1"));

    There really isnt' a need to round the number itself (unless you need it rounded).

    Note that you can't specify exact values in floating point numbers.  For details, I'd recommend reading the classic document "What Every Computer Scientist Should Know About Floating Point Arithmetic" at http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Rajat Kaushal Sunday, April 28, 2013 4:03 AM
    • Marked as answer by Taibc Thursday, May 2, 2013 12:32 AM
    Sunday, April 28, 2013 3:10 AM

All replies

  • You need to change how you display the floating point value:

    MessageBox.Show(result.ToString("F1"));

    There really isnt' a need to round the number itself (unless you need it rounded).

    Note that you can't specify exact values in floating point numbers.  For details, I'd recommend reading the classic document "What Every Computer Scientist Should Know About Floating Point Arithmetic" at http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Rajat Kaushal Sunday, April 28, 2013 4:03 AM
    • Marked as answer by Taibc Thursday, May 2, 2013 12:32 AM
    Sunday, April 28, 2013 3:10 AM
  • Thanks Reed Copsey, it is successful

    What is "F1" in your code ?


    • Edited by Taibc Sunday, April 28, 2013 4:12 AM
    Sunday, April 28, 2013 4:12 AM
  • That is a Format string that defines how the Float should be transformed to a String. There are many different Format Strings:

    http://msdn.microsoft.com/en-us/library/f71z6k0c.aspx


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2

    Sunday, April 28, 2013 10:17 AM
  • That is a Format string that defines how the Float should be transformed to a String. There are many different Format Strings:

    http://msdn.microsoft.com/en-us/library/f71z6k0c.aspx


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2


    Yes, thank you !
    Thursday, May 2, 2013 12:31 AM