Restricting the length of strings...

I'm wondering if it is possible to restrict the length of a string produced by the String.valueOf(double) method. Here is an example:
public class DoubleTest
     public static void main(String[] args)
          double d = 20.0;
          double d2 = 2.4;
          double value = (d/d2);
          String doubleString = String.valueOf(value);
          System.out.println(value);
}This code will output "8.333333333333334" when run. Is there a way to restrict it to fewer decimal places, for example: "8.34"?
Thanks a lot,
Eric

If you use DecimalFormat, you can specify the number of digits after the decimal point by using a 'pattern' in the constructor to DecimalFormat.
Use '#' in the pattern for digits which will not show any leading zeros.
Use '0' in the pattern for digits which will show zeros - this is the one to use after the decimal point to show how many decimal places you want showing.
This format will round the numbers either up or down depending on which is nearer.
See example below for usage :
import java.text.*;
public class DoubleTest{
     public static void main(String[] args)     {
          double d = 400000.0;
          double d2 = 2.4;
          double value = (d/d2);
          DecimalFormat df1 = new DecimalFormat("#.000");
        System.out.println(df1.format(value));
}This returns 166666.667 (i.e. 3 places after the decimal, rounded up).
Regards,
Fintan

Similar Messages

  • How to restrict the length of the input?

    Hi all, could any one tell me how to restrict the length of the input string? My SOA Suite is 10.1.3.1
    I tried the following; getting an error.
    <element name="RestrictLengthProcessRequest">
    <simpleType name="SSN">
    <restriction base="string">
    <length value="10"/>
    </restriction>
    </simpleType>
    where RestrictLengthProcessRequest is the message name of the corresponding .wsdl and SSN is the input whose length is to be restricted.
    The error is : 'Attribute name not defined on element simpleType'
    Thanks in advance.
    Edited by: user11275112 on Aug 27, 2009 11:44 PM

    Hi swathi,
    For this you have to create a simple data type. No need of writing a code.
    Go to Dictionaries -> Local Dictionary -> Data Type - > Simple Type - > Right click and "Create Simple Type".
    Here you should create a Simple type with String as built-in Type. Here you will also see the Length Constraints option.
    Set the value of maximum length and minimum length. In your case set the value of maximum length to 10. At runtime this will not allow the user to enter more than 10 characters.
    Now create an attribute and bind it to this newly created simple type. Bind the value of the input field with this particular attribute.
    Regards
    Manohar

  • How to restrict the length of input field

    Hi,
    How to restrict the length of input field. That is we should not be able to enter more thatn 10 charecters.
    Regards,
    H.V.Swathi

    Hi swathi,
    For this you have to create a simple data type. No need of writing a code.
    Go to Dictionaries -> Local Dictionary -> Data Type - > Simple Type - > Right click and "Create Simple Type".
    Here you should create a Simple type with String as built-in Type. Here you will also see the Length Constraints option.
    Set the value of maximum length and minimum length. In your case set the value of maximum length to 10. At runtime this will not allow the user to enter more than 10 characters.
    Now create an attribute and bind it to this newly created simple type. Bind the value of the input field with this particular attribute.
    Regards
    Manohar

  • Restricting the length of an input field

    Hi, I'm trying to display some form of component on screen that only allows a specific number of characters to be entered into it. I tried initialising a JTextField with a length but this refers to the display length as opposed to the maximum number of characters that can be entered. For example, if I want to ask a user to enter a year, I only want them to enter up to 4 characters.
    Any ideas ?

    Another way is to create your own Document, for
    example, by extending PlainDocument and overriding the
    insertString() method. The 1.3 docs for JTextField
    give an example for a JTextField that makes all input
    upper case. This approach is more complex but may
    provide more pleasing results.Use this method, otherwise you can paste more than 4 characters into the JTextField...

  • Restricting editable length of a JTable column

    Hello,
    Is there a way to restrict the length of a JTable cell when being edited? i.e. I have a column of my JTable that should only contain strings of 3 characters at the most.
    Many thanks,
    Ian.

    Hello,
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestCustomTable extends JFrame implements TableData
         public static void main(String[] args)
              new TestCustomTable();
         private JTable customTable = null;
         public TestCustomTable()
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initTable();
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         private void initTable()
              customTable = new JTable(DATA, COLHEADS);
              //create custom-TextField with maximum Characters
              MaxCharTextField maxCharField = new MaxCharTextField(3);
              DefaultCellEditor maxCharEditor = new DefaultCellEditor(maxCharField);
                    //all Objects in the table have the same restriction
              customTable.setDefaultEditor(Object.class, maxCharEditor);
              getContentPane().add(new JScrollPane(customTable));
    * MaxCharTextField.java
    class MaxCharTextField extends JTextField
         int maxChar = 10;
         public MaxCharTextField()
              super();
         public MaxCharTextField(int maxChar)
              super();
              this.maxChar = maxChar;
         public void setMaxChar(int maxChar)
              this.maxChar = maxChar;
         public int getMaxChar()
              return maxChar;
         protected Document createDefaultModel()
              return new PlainDocument()
                   public void insertString(int offs, String str, AttributeSet a)
                        throws BadLocationException
                        int length = getLength();
                        // fields don't want to have multiple lines.  We may provide a field-specific
                        // model in the future in which case the filtering logic here will no longer
                        // be needed.
                        Object filterNewlines = getProperty("filterNewlines");
                        if ((filterNewlines instanceof Boolean)
                             && filterNewlines.equals(Boolean.TRUE))
                             if ((str != null) && (str.indexOf('\n') >= 0))
                                  StringBuffer filtered = new StringBuffer(str);
                                  int n = filtered.length();
                                  for (int i = 0; i < n; i++)
                                       if (filtered.charAt(i) == '\n')
                                            filtered.setCharAt(i, ' ');
                                  str = filtered.toString();
                        if ((length += str.length()) > maxChar)
                             //don't insert if current chars > max chars
                             return;
                        super.insertString(offs, str, a);
    * TableData.java
    * test-data for custom table
    interface TableData
         public static final Object[][] DATA =
              { { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {
                   "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)
                   "Kathy",
                        "Walrath",
                        "Chasing toddlers",
                        new Integer(2),
                        new Boolean(false)
                   "Sharon",
                        "Zakhour",
                        "Speed reading",
                        new Integer(20),
                        new Boolean(true)
                   "Angela",
                        "Lih",
                        "Teaching high school",
                        new Integer(4),
                        new Boolean(false)
         public static final String[] COLHEADS =
              { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };
    }regards,
    Tim

  • The length of the password entry field in the BEx Analyser

    Hi,
    The password is 8 characters in the BW system.
    When users changing their newly assigned passwords. When logging into the BEx Analyser, and prompted to change the password, a password entry box is displayed, with an entry field longer then 8 characters. Some users are therefore entering passwords longer then 8 characters. This is fine when they first login, but when they try come back to the system, their logon fails.
    Can something be done to restrict the length of the password entry field in the BEx Analyser?
    Many Thanks
    Jonathan

    Hi Jonathan
    we are having the same problem - did you find a way to resolve this?  I did not find any SAP notes referring to the issue.
    Regards
    Hayley

  • How to get the length of a field value, not the length of DB's CHAR(20)

    Hello.
    I'm trying to handle a String from my DataBase and get its length:
    String myName;
    int i;
    PreparedStatement sql = Conn.prepareStatement("SELECT NAME FROM MY_TABLE");
    ResultSet results = sql.executeQuery();
    results.next();
    myName = results.getString("NAME");
    i = myName.length();
    out.println("The value is " + myName + " and the length is " + String.valueOf(i) );
    I get:
    " The value is Tom and the lengh is 20 "
    20 is the length of the field (it's a CHAR (20) ), but I would like to get the length
    of 'Tom'.
    On other hand, I would like to detect if this value is 'Tom' or not, but trying with:
    if (myName.equals("Tom")) {...}
    or
    if (myName == "Tom") {...}
    There is no response.
    Any experience?

    myName = results.getString("NAME");
    if(myName!=null) myName = myName.trim(); //Take out trailing spaces
    i = myName.length();Sudha

  • How to control the length of tax number

    Hi,expert,
    I want to control the length of tax number regarding to some  tax category in 'CONTROL' tabpage of newing organization.
    Could some expert tell me how to customize it?
    In my former opinion,I think this should be customized in SAP  NetWeaver->General settings->Set Countries->Set Country- Specific Checks.
    But after I restrict the length check,test result shows  failure.
    For example, tax number1 of BO(Bolivia) should be 10  characters at most. After the length check is set as '10',the  tax number in BP could still contain more than 10 characters.
    So could anybody tell me where's the problem,am I think  wrong? Or did I miss some other

    Hi,
    Did you check the view V_TFKTAXNUMTYPE in SM30? In this view you can see the FM that consists the tax code for BO.
    If the FM does not work for you, you can copy and do the necessary changes!
    Hope this helps!
    Best regards,
    Caíque Escaler

  • Restrict the input string length

    Hi, how do I restrict the input string length in a JTextField. Suppose if I want my text field to accept only 4 characters, the fifth character I try to enter shouldn't be accepted in the field.
    Thanks,
    Kalyan.

    This is for 6 characters limit
    //create a JTextField that is six characters long
    JTextField textField = new JTextField(new FixedNumericDocument(5,true),"", 6);
    Here boolean true means only numeric. set to false to take in alphanumeric.
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class FixedNumericDocument extends PlainDocument {
    private int maxLength = 9999;
    private boolean numericOnly;
    public FixedNumericDocument(int maxLength, boolean numericOnly) {
    super();
    this.maxLength = maxLength;
    this.numericOnly = numericOnly;
    //this is where we'll control all input to our document.
    //If the text that is being entered passes our criteria, then we'll just call
    //super.insertString(...)
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (getLength() + str.length() > maxLength) {
    return;
    else {
    try {
    if (numericOnly) {
    Integer.parseInt(str);
    //if we get here then str contains only numbers
    //so that it can be inserted
    super.insertString(offset, str, attr);
    catch(NumberFormatException exp) {
    return;
    return;

  • How do i find the length of a string??

    trying to use the substring, I know the beginIndex (in my case 10), but the string will vary in size and so i need to find the last character and set it as the endIndex, how do i do this?
    public String substring(int beginIndex,
    int endIndex)Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
    Examples:
    "hamburger".substring(4, 8) returns "urge"
    "smiles".substring(1, 5) returns "mile"
    Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.
    Returns:
    the specified substring.

    Hi
    To substring the string where u know the begin index and want to extract till the end use the following function from the String class of the java.lang package
    String substring(int beginindex);
    String test = "Hello";
    String xx = test.substring(1);
    The Value stored in xx will be ello
    This is in case u need till the end of the String
    If wanna skip the last character u can
    use
    String substring(int beginindex,int endindex);
    String test = "Hello";
    String xx = test.substring(1,test.length()-1);
    The Value stored in xx will be ell

  • How is the length of a string calculated in Java?  and JavaScript?

    Hi all,
    Do any of you know how the length of a string is being calculated in Java and JavaScript? For example, a regular char is just counted as 1 char, but sometimes other chars such as CR, LF, and CR LF are counted as two. I know there are differences in the way Java and JavaScript calculate the length of a string, but I can't find any sort of "rules" on those anywhere online.
    Thanks,
    Yim

    What's Unicode 4 got to do with it? 1 characteris 1
    character is 1 character.
    strings now contain (and Java chars also) is
    UTF-16 code units rather than Unicode characters
    or
    code points. Unicode characters outside the BMPare
    encoded in Java as two or more code units. So it would seem that in some cases, a single
    "character" on the screen, will require two charsto
    represent it.So... you're saying that String.length() doesn't
    account for that? That sux. I don't know. I'm just making infrerences (==WAGs) based on what DrClap said.
    I assume it would return the number of chars in the array, rather than the number of symbols (glyphs?) this translates into. But I might have it bass ackwards.

  • How to get the length in bytes of a string

    My string has both latin (1 byte) and chinese (2 bytes).
    My program is in unicode system.
    How to measure the length in bytes of the string?
    the xlen function does not work.

    Hello,
    parameters : p_str type string.
    data : len type i.
    len = strlen( p_str ).
    write : / len.
    With Regards,
    BVS
    Hi BSV, your code return the number of characters not bytes.
    Remember chinese character in US are encoded with 2 bytes.
    And my string contain both latin and chinese characters.
    thanks

  • How to restrict the copy & paste in string control?

    In my application user name & password string controls are there.After typing the username in string control it is copied and paste it in password string control .
    I like to restrict the string copy from one string control  & paste it into another string control ?
    How to do this?
    Kumar.
    Attachments:
    login.vi ‏11 KB

    These images illustrate anoth approach to inhibit the copying of text which is available in LV 8.2 (maybe 8.0)
    Ben
    Message Edited by Ben on 12-07-2006 10:12 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    Edit_RT_Shortcut.JPG ‏60 KB
    Short_cut_Menu_edit.JPG ‏30 KB

  • Is there any restriction on the length of all Primary keys in a table

    Hi all,
    Is there any restriction on the length of all Primary keys in a data base table?
    i have some 10 fields as primary key in a DB table and length exceeds 120 and getting a warning.
    Please let me know will there be any problems in future with respect to the same?
    With regards,
    Sumanth

    Well actually there are constraints like
    Total of internal lengths of all primary key columns        1024 Bytes
    Number of primary key columns per table                     512
    For other information about SAP database please refer to http://sapdb.org/sap_db_features.htm  
    Thanks & Regards,
    Vivek Gaur
    Alwayz in high spirits

  • How can i get the length of a string with Simplified Chinese?

    when i use eventwriter to add content to a xmldocument,there are some chinese simplified string in it,i use String.length() for the length ,but it is not correct~how can i get the right length for eventwriter?

    Below is a simple patch for this problem. Using this patch you need to pass 0 as the length argument for any XmlEventWriter interfaces that take a string length.
    Regards,
    George
    diff -c dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp
    *** dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp    Fri Nov  3 12:26:11 2006
    --- dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp      Thu Mar 15 13:58:13 2007
    *** 234,239 ****
    --- 234,241 ----
            CHECK_NULL(text);
            CHECK_SUCCESS();
    +       if (!length)
    +               length = ::strlen((const char *)text);
            if (!_current)
                    throwBadWrite("writeText: requires writeStartDocument");
            try {
    *** 413,418 ****
    --- 415,422 ----
            CHECK_NULL(dtd);
            CHECK_SUCCESS();
    +       if (!length)
    +               length = ::strlen((const char *)dtd);
            if (_current) {
                    if (!_current->isDoc())
                            throwBadWrite("writeDTD: must occur before content");
    diff -c dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsWriter.cpp dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsWriter.cpp
    *** dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsWriter.cpp Tue Jan  2 16:01:14 2007
    --- dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsWriter.cpp   Thu Mar 15 13:59:25 2007
    *** 326,331 ****
    --- 326,333 ----
                    needsEscape = false;
            else
                    needsEscape = true;
    +       if (!length)
    +               length = ::strlen((const char *)chars);
            writeTextWithEscape(type, chars, length, needsEscape);
    *** 336,341 ****
    --- 338,345 ----
                                  bool needsEscape)
            if(_entCount == 0) {
    +               if (!len)
    +                       len = ::strlen((const char *)chars);
                    if ((type == XmlEventReader::Characters) ||
                        (type == XmlEventReader::Whitespace)) {
                            char *buf = 0;
    *** 381,386 ****
    --- 385,392 ----
      NsWriter::writeDTD(const unsigned char *data, int len)
            if(_entCount == 0) {
    +               if (!len)
    +                       len = ::strlen((const char *)data);
                    _stream->write(data, len);
      }

Maybe you are looking for

  • Using ajax/servlets, different behaviour with different systems

    I have written a small web application using servlets and ajax. I used the tomcat bundled with netbeans for deploying it. In the front end I create a timer which keeps running. I also have a form containing a paragraph that displays a question, follo

  • S.m.a.r.t says disks is failing only had my iMac 6 months takes longer to do anything

    do i clear my contacts ect. or just take back

  • Failure of Epson R2880 to print

    I am very frustrated at the failure of Adobe to help me sort a problem which appears to be of their making. My operating system in Mac Mavericks OSX 10.9 Until very recently all was fine printing from CS5 to my printer, then an error message occurred

  • HWNDBasedPanelView UID:102242

    Always when I open InDesing I see this window with title: HWNDBasedPanelView UID:102242 What is it? I have windows 7 professional and Indesign cs6 ver 8.0.1

  • Line Drawings

    I need to create some simple B&W line maps.  I would like to use a jpg of a colored map, then draw (trace) the lines over the map (in another layer?) and then save only the drawn lines. Doesn't need to be automatic, just want to know if I can trace e