简体   繁体   中英

Converting double to string in java for a netbeans gui

i want the total text field (txtTotal) to display the running total of the cost of the food order. however i get an error as it says that the last line is incorrect because you cannot convert a double to string. What should I do??

    txtOrder.setText("Soup of the Day");
    txtPrice.setText("€4.00");
    total=total+crapClaws;
    txtTotal.setText(total);

You can convert a double to a String in a number of ways. Any of the following will work:

txtTotal.setText(String.valueOf(total));
txtTotal.setText(Double.toString(total));
txtTotal.setText("" + total);

The first to solutions call a method which converts a double into a String explicitly; the last solution uses the fact that Java lets you concatenate an arbitrary value with a string with a string as result.

Having said the above, however, you should know that it is a very bad idea to use double to represent currency values. Doubles use binary floating point numbers, and this means that a lot of values cannot be exactly represented. For example, 0.1 has no exact representation as a double. If you calculate with the currency values a lot, this will almost certainly lead to unexpected results.

You should use BigDecimal to represent currency values, or store the number of cents in a long or int .

Just write:

txtTotal.setText(String.valueOf(total));

the method setText is expecting a String value, but you are giving it a double . You need to convert that double. Some methods, like System.out.println , provide convenience overloads that do take many different types, so you may be used to having this "just work", but that isn't the case with setText .

...just an aside, you might want to doublecheck that the soup of the day is in fact crapClaws .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM