how to throw the characters?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iurceg
    New Member
    • Mar 2012
    • 3

    #1

    how to throw the characters?

    I have a number of type double 12.2301000
    I need to get 12.23

    p.s. I do not need rounding.
  • PsychoCoder
    Recognized Expert Contributor
    • Jul 2010
    • 465

    #2
    You can use String.Format like this to only allow 2 decimal places:

    Code:
    String.Format("{0:0.00}", 123.4567);
    You can also use regular expressions in the KeyPress event of your textbox like this:

    Code:
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    	if (char.IsNumber(e.KeyChar) || e.KeyChar=='.')
    	{
    		if (Regex.IsMatch(textBox1.Text, "^\\d*\\.\\d{2}$")) 
    			e.Handled=true;
    	}
    	else 
    	e.Handled = e.KeyChar != (char)Keys.Back;
    }

    Comment

    • iurceg
      New Member
      • Mar 2012
      • 3

      #3
      PsychoCoder
      Thanks for response but the first version is rounded.
      Code:
      String.Format("{0:0.00}", 123.4567);
      The result is: 123.46 but i need 123.45 :)

      Comment

      • Stewart Ross
        Recognized Expert Moderator Specialist
        • Feb 2008
        • 2545

        #4
        @iurceg: what you are really asking is that the result should be rounded down in all cases, not rounded up when the next digit is 5 or more as is the normal practice. It is not correct to say you do not need rounding - truncation is still a form of rounding of the answer.

        I'm not a c# person, so I don't know how to express it in c#, but one way to truncate a value to two decimal places is to multiply the double by 100, store the result in a longint, then divide the longint value by 100 to obtain your result (effectively truncating to two decimal places max).

        You could also use integer division in place of the use of a longint, or whatever the C# equivalent of the VB Int function is to accomplish the same effect.

        -Stewart

        Comment

        Working...