Search Results

Search found 4591 results on 184 pages for 'tostring'.

Page 3/184 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • toString() in Java

    - by Allain Lalonde
    A lead developer on my project has taken to referring to the project's toString() implementations as "pure cruft" and is looking to remove them from the code base. I've said that doing so would mean that any clients wishing to display the objects would have to write their own code to convert the object to string, but that was answered with "yes they would". Now specifically, the objects in this system are graphic elements like rectangles, circles, etc and the current representation is to display x, y, scale, bounds, etc... So, where does the crowd lie? When should you and when shouldn't you implement toString?

    Read the article

  • Round-twice error in .NET's Double.ToString method

    - by Jeppe Stig Nielsen
    Mathematically, consider for this question the rational number 8725724278030350 / 2**48 where ** in the denominator denotes exponentiation, i.e. the denominator is 2 to the 48th power. (The fraction is not in lowest terms, reducible by 2.) This number is exactly representable as a System.Double. Its decimal expansion is 31.0000000000000'49'73799150320701301097869873046875 (exact) where the apostrophes do not represent missing digits but merely mark the boudaries where rounding to 15 resp. 17 digits is to be performed. Note the following: If this number is rounded to 15 digits, the result will be 31 (followed by thirteen 0s) because the next digits (49...) begin with a 4 (meaning round down). But if the number is first rounded to 17 digits and then rounded to 15 digits, the result could be 31.0000000000001. This is because the first rounding rounds up by increasing the 49... digits to 50 (terminates) (next digits were 73...), and the second rounding might then round up again (when the midpoint-rounding rule says "round away from zero"). (There are many more numbers with the above characteristics, of course.) Now, it turns out that .NET's standard string representation of this number is "31.0000000000001". The question: Isn't this a bug? By standard string representation we mean the String produced by the parameterles Double.ToString() instance method which is of course identical to what is produced by ToString("G"). An interesting thing to note is that if you cast the above number to System.Decimal then you get a decimal that is 31 exactly! See this Stack Overflow question for a discussion of the surprising fact that casting a Double to Decimal involves first rounding to 15 digits. This means that casting to Decimal makes a correct round to 15 digits, whereas calling ToSting() makes an incorrect one. To sum up, we have a floating-point number that, when output to the user, is 31.0000000000001, but when converted to Decimal (where 29 digits are available), becomes 31 exactly. This is unfortunate. Here's some C# code for you to verify the problem: static void Main() { const double evil = 31.0000000000000497; string exactString = DoubleConverter.ToExactString(evil); // Jon Skeet, http://csharpindepth.com/Articles/General/FloatingPoint.aspx Console.WriteLine("Exact value (Jon Skeet): {0}", exactString); // writes 31.00000000000004973799150320701301097869873046875 Console.WriteLine("General format (G): {0}", evil); // writes 31.0000000000001 Console.WriteLine("Round-trip format (R): {0:R}", evil); // writes 31.00000000000005 Console.WriteLine(); Console.WriteLine("Binary repr.: {0}", String.Join(", ", BitConverter.GetBytes(evil).Select(b => "0x" + b.ToString("X2")))); Console.WriteLine(); decimal converted = (decimal)evil; Console.WriteLine("Decimal version: {0}", converted); // writes 31 decimal preciseDecimal = decimal.Parse(exactString, CultureInfo.InvariantCulture); Console.WriteLine("Better decimal: {0}", preciseDecimal); // writes 31.000000000000049737991503207 } The above code uses Skeet's ToExactString method. If you don't want to use his stuff (can be found through the URL), just delete the code lines above dependent on exactString. You can still see how the Double in question (evil) is rounded and cast.

    Read the article

  • Convert user input into ToString() method inside FlowDocument in Workflow 4.0

    - by Jon Ownbey
    I have a Workflow 4.0 app that generates emails. In a dialog for creating the email body the user needs to be able to input some string value representing an existing wf instance variable to be inserted as a string at runtime. So they input something like: Email body text including <. (say ExistingVariable is an int or something like that) Any helpful hints for how to convert this text with a ToString() at runtime?

    Read the article

  • Double.ToString with N Number of Decimal Places

    - by Ngu Soon Hui
    I know that if we want to display a double as a two decimal digit, one would just have to use public void DisplayTwoDecimal(double dbValue) { Console.WriteLine(dbValue.ToString("0.00")); } But how to extend this to N decimal places, where N is determined by the user? public void DisplayNDecimal(double dbValue, int nDecimal) { // how to display }

    Read the article

  • return new string vs .ToString()

    - by Leroy Jenkins
    Take the following code: public static string ReverseIt(string myString) { char[] foo = myString.ToCharArray(); Array.Reverse(foo); return new string(foo); } I understand that strings are immutable, but what I dont understand is why a new string needs to be called return new string(foo); instead of return foo.ToString(); I have to assume it has something to do with reassembling the CharArray (but thats just a guess). Whats the difference between the two and how do you know when to return a new string as opposed to returning a System.String that represents the current object?

    Read the article

  • toString() Method question

    - by cdominguez13
    I've been working on this assignemnt here's code: public class Student { private String fname; private String lname; private String studentId; private double gpa; public Student(String studentFname,String studentLname,String stuId,double studentGpa) { fname = studentFname; lname = studentLname; studentId = stuId; gpa = studentGpa; } public double getGpa() { return gpa; } public String getStudentId() { return studentId; } public String getName() { return lname + ", " + fname; } public void setGpa(double gpaReplacement) { if (gpaReplacement >= 0.0 && gpaReplacement <= 4.0) gpa = gpaReplacement; else System.out.println("Invalid GPA! Please try again."); System.exit(0); } } Now I need to create a toString() method that returns a String formatted something like this: Name: Wilson, Mary Ann ID number: 12345 GPA: 3.5

    Read the article

  • concatenation output problem (toString Array) - java

    - by dowln
    Hello, I am trying to display the output as "1(10) 2(23) 3(29)" but instead getting output as "1 2 3 (10)(23)(29)". I would be grateful if someone could have a look the code and possible help me. I don't want to use arraylist. the code this // int[] Groups = {10, 23, 29}; in the constructor public String toString() { String tempStringB = ""; String tempStringA = " "; String tempStringC = " "; for (int x = 1; x<=3; x+=1) { tempStringB = tempStringB + x + " "; } for(int i = 0; i < Group.length;i++) { tempStringA = tempStringA + "(" + Groups[i] + ")"; } tempStringC = tempStringB + tempStringA; return tempStringC; }

    Read the article

  • Generating equals / hashcode / toString using annotation

    - by Bruno Bieth
    I believe I read somewhere people generating equals / hashcode / toString methods during compile time (using APT) by identifying which fields should be part of the hash / equality test. I couldn't find anything like that on the web (I might have dreamed it ?) ... That could be done like that : public class Person { @Id @GeneratedValue private Integer id; @Identity private String firstName, lastName; @Identity private Date dateOfBirth; //... } For an entity (so we want to exlude some fields, like the id). Or like a scala case class i.e a value object : @ValueObject public class Color { private int red, green, blue; } Not only the file becomes more readable and easier to write, but it also helps ensuring that all the attributes are part of the equals / hashcode (in case you add another attribute later on, without updating the methods accordingly). I heard APT isn't very well supported in IDE but I wouldn't see that as a major issue. After all, tests are mainly run by continuous integration servers. Any idea if this has been done already and if not why ? Thanks

    Read the article

  • Permission denied to access property 'toString'

    - by Anders
    I'm trying to find a generic way of getting the name of Constructors. My goal is to create a Convention over configuration framework for KnockoutJS My idea is to iterate over all objects in the window and when I find the contructor i'm looking for then I can use the index to get the name of the contructor The code sofar (function() { constructors = {}; window.findConstructorName = function(instance) { var constructor = instance.constructor; var name = constructors[constructor]; if(name !== undefined) { return name; } var traversed = []; var nestedFind = function(root) { if(typeof root == "function" || traversed[root]) { return } traversed[root] = true; for(var index in root) { if(root[index] == constructor) { return index; } var found = nestedFind(root[index]); if(found !== undefined) { return found; } } } name = nestedFind(window); constructors[constructor] = name; return name; } })(); var MyApp = {}; MyApp.Foo = function() { }; var instance = new MyApp.Foo(); console.log(findConstructorName(instance)); The problem is that I get a Permission denied to access property 'toString' Exception, and i cant even try catch so see which object is causing the problem Fiddle http://jsfiddle.net/4ZwaV/

    Read the article

  • e.Row.Tag .ToString

    - by prince23
    hi, Child data grid is not showing the values in the page for the child datagrid I am binding with an list <sdk:DataGrid MinHeight="100" x:Name="contacts" Margin="51,21,88,98" RowDetailsVisibilityChanged="contacts_RowDetailsVisibilityChanged" LoadingRowDetails="contacts_LoadingRowDetails" RowDetailsVisibilityMode="VisibleWhenSelected" MouseLeftButtonUp="contacts_MouseLeftButtonUp" MouseLeftButtonDown="contacts_MouseLeftButtonDown"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding EmployeeID}" Header="ID" /> <sdk:DataGridTextColumn Binding="{Binding EmployeeFName}" Header="Fname" /> <sdk:DataGridTextColumn Binding="{Binding EmployeeLName}" Header="LName" /> <sdk:DataGridTextColumn Binding="{Binding EmployeeMailID}" Header="MailID" /> </sdk:DataGrid.Columns> <sdk:DataGrid.RowDetailsTemplate> <DataTemplate> <sdk:DataGrid x:Name="dgrdRowDetail" Width="200" AutoGenerateColumns="False" HorizontalAlignment="Center" IsReadOnly="True"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="CompanyName" Binding="{Binding Company name}"/> <sdk:DataGridTextColumn Header="CompanyName" Binding="{Binding EmpID}"/> </sdk:DataGrid.Columns> </sdk:DataGrid> </DataTemplate> </sdk:DataGrid.RowDetailsTemplate> </sdk:DataGrid> I am having 2 grids "contacts" and "dgrdRowDetail" globally i have defined an variable like this:- DataGrid dgrdRowDetail; in the contacts_RowDetailsVisibilityChanged event I have this code if (e.Row.DataContext != null) { string strEmpID = ((SilverlightApplication1.DBServiceEMP.Employee)((e.DetailsElement).DataContext)).EmployeeID; dgrdRowDetail = (DataGrid)e.DetailsElement.FindName("dgrdRowDetail"); // here i am finding the child datgrid control in contacts datagrid // then in dgrdRowDetail i will be binding this grid with new values if (strEmpID != null) { int EmpID = Convert.ToInt32(strEmpID.ToString()); DBServiceEmp.GetEmployeeIDCompleted += new EventHandler<GetEmployeeIDCompletedEventArgs>(DBServiceEmp_GetEmployeeIDCompleted); DBServiceEmp.GetEmployeeIDAsync(EmpID); } } this is my method void DBServiceEmp_GetEmployeeIDCompleted(object sender, GetEmployeeIDCompletedEventArgs e) { // List<Employee> Employes = new List<Employee>(); List<Employee> rows = new List<Employee>(); for (int i = 0; i < e.Result.Count; i++) { rows.Add(e.Result[i]); } dgrdRowDetail.ItemsSource = rows; // here i am binding the child datagrid with new data source } dgrdRowDetail.ItemsSource = rows// what ever rows i am binding to dgrdRowDetail are not shown in the page if i check the rows i am able to see the value ther. but in the child grid it is not reflecting plz plz help me out i am struck thanks in advance prince

    Read the article

  • php 5.1.6 magic __toString method

    - by NachoF
    In codeigniter Im trying to use this plugin which requires I implement a toString method in my models. My toString method simply does return $this->name On my local machine with php 5.3 everything works just fine but on the production server with php 5.1.6 it shows "Object id#48" where the value of the name property of that object should appear..... I found something about the problem here but I still dont understand... How can I fix this?

    Read the article

  • Web Application : How to upload multiple images at a time

    - by SAMIR BHOGAYTA
    //First add image control into the web form how many you want to upload images at a time //Add one button //Write the below code into the button_click event if (FileUpload1.HasFile) { string imagefile = FileUpload1.FileName; if (CheckFileType(imagefile) == true) { Random rndob = new Random(); int db = rndob.Next(1, 100); filename = System.IO.Path.GetFileNameWithoutExtension(imagefile) + db.ToString() + System.IO.Path.GetExtension(imagefile); String FilePath = "images/" + filename; FileUpload1.SaveAs(Server.MapPath(FilePath)); objimg.ImageName = filename; Image1(); if (Session["imagecount"].ToString() == "1") { Img1.ImageUrl = FilePath; ViewState["img1"] = FilePath; } else if (Session["imagecount"].ToString() == "2") { Img1.ImageUrl = ViewState["img1"].ToString(); Img2.ImageUrl = FilePath; ViewState["img2"] = FilePath; } else if (Session["imagecount"].ToString() == "3") { Img1.ImageUrl = ViewState["img1"].ToString(); Img2.ImageUrl = ViewState["img2"].ToString(); Img3.ImageUrl = FilePath; ViewState["img3"] = FilePath; } else if (Session["imagecount"].ToString() == "4") { Img1.ImageUrl = ViewState["img1"].ToString(); Img2.ImageUrl = ViewState["img2"].ToString(); Img3.ImageUrl = ViewState["img3"].ToString(); Img4.ImageUrl = FilePath; ViewState["img4"] = FilePath; } else if (Session["imagecount"].ToString() == "5") { Img1.ImageUrl = ViewState["img1"].ToString(); Img2.ImageUrl = ViewState["img2"].ToString(); Img3.ImageUrl = ViewState["img3"].ToString(); Img4.ImageUrl = ViewState["img4"].ToString(); Img5.ImageUrl = FilePath; ViewState["img5"] = FilePath; } } } //execption handling else { lblErrMsg.Visible = true; lblErrMsg.Text = ""; lblErrMsg.Text = "please select a file"; } } //if file extension belongs to these list then only allowed public bool CheckFileType(string filename) { string ext; ext = System.IO.Path.GetExtension(filename); switch (ext.ToLower()) { case ".gif": return true; case ".jpeg": return true; case ".jpg": return true; case ".bmp": return true; case ".png": return true; default: return false; } }

    Read the article

  • Returning an array from an activity

    - by Boardy
    I am currently working on an android project and I want to be able to startActivityForResult so that I can return an array of. The array is an ArrayList<Spanned> lets say its called myArray. From what I've read I can't return an array directly from the activty using the set result so I was thinking that once the array has added all the data to the array, I can then call the toString function on it, i.e. myArray.toString(). If I do this, I have no idea how I can then convert this back into the original ArrayList<Spanned>. Thanks for any help you can provide.

    Read the article

  • Arrays (toString) not output correctly

    - by DiscoDude
    Hello, Actually this tread is continuing from the other one. There wasn't enough characters to continue there. Anyway. the problem is that the output is "1(10) 2(23) 3(29)". Even though I could return string for the array values (10,23,29) and used string reference as 1, 2 and 3. My question is it possible to return index values 1,2,3 and as well as array values. Am I making an sense. Here is what I have done... // int[] groups = {10, 23, 29}; in the constructor String tempA = ""; String tempB = " "; int[] temp = new int[4]; int length = groups.length; for (int j = 0; j < length; j++) { temp[j] = groups[j]; tempB = tempB + "("+goups+")"; } groups = temp; Arrays.sort(coingroups); for(int i = 1; i < groups.length;i++) { tempA = tempA+" "+(i)+ "("+groups[i]+")"; } return tempA;

    Read the article

  • Map to String in Java

    - by Dan
    When I do System.out.println(map) in Java, I get a nice output in stdout. How can I obtain this same string representation of a Map in a variable without meddling with standard output? Something like String mapAsString = Collections.toString(map)?

    Read the article

  • The counter doesnt seem to increase when ever the edittext changes

    - by Mabulhuda
    Im using Edit-texts and i need when ever an edit-text is changed to increment a counter by one but the counter isnt working , I mean the app starts and everything but the counter doesnt seem to change please help here is the code public class Numersys extends Activity implements TextWatcher { EditText mark1 ,mark2, mark3,mark4,mark5,mark6 , hr1 ,hr2,hr3,hr4,hr5,hr6; EditText passed, currentavg; TextView tvnewavg ; Button calculate; double marks , curAVG , NewAVG ; String newCumAVG; int counter , hrs , curHr , NewHr; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.numersys); mark1=(EditText)findViewById(R.id.mark1n); mark2=(EditText)findViewById(R.id.mark2n); mark3=(EditText)findViewById(R.id.mark3n); mark4=(EditText)findViewById(R.id.mark4n); mark5=(EditText)findViewById(R.id.mark5n); mark6=(EditText)findViewById(R.id.mark6n); hr1=(EditText)findViewById(R.id.ethour1); hr2=(EditText)findViewById(R.id.ethour2); hr3=(EditText)findViewById(R.id.ethour3); hr4=(EditText)findViewById(R.id.ethour4); hr5=(EditText)findViewById(R.id.ethour5); hr6=(EditText)findViewById(R.id.ethour6); passed=(EditText)findViewById(R.id.etPassCn); currentavg=(EditText)findViewById(R.id.etCavgn); tvnewavg=(TextView)findViewById(R.id.tvcAVGn); mark1.addTextChangedListener(this); mark2.addTextChangedListener(this); mark3.addTextChangedListener(this); mark4.addTextChangedListener(this); mark5.addTextChangedListener(this); mark6.addTextChangedListener(this); calculate=(Button)findViewById(R.id.bAvgCalcn); @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch(arg0.getId()) { case 0: break; case 1: hrs=Integer.valueOf(hr1.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case 2: hrs=Integer.valueOf(hr1.getText().toString())+Integer.valueOf(hr2.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()) +Double.valueOf(mark2.getText().toString())*Integer.valueOf(hr2.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case 3: hrs=Integer.valueOf(hr1.getText().toString())+Integer.valueOf(hr2.getText().toString()) +Integer.valueOf(hr3.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()) +Double.valueOf(mark2.getText().toString())*Integer.valueOf(hr2.getText().toString()) +Double.valueOf(mark3.getText().toString())*Integer.valueOf(hr3.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case R.id.bAvgCalcn: newCumAVG=String.valueOf(NewAVG); tvnewavg.setText(newCumAVG); } } }); } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub if(mark1.hasFocus()) { counter = counter+1; } if(mark2.hasFocus()) { counter = counter+1; } if(mark3.hasFocus()) { counter = counter+1; } if(mark4.hasFocus()) { counter = counter+1; } if(mark5.hasFocus()) { counter = counter+1; } if(mark6.hasFocus()) { counter = counter+1; } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >