kostas
kostas

Reputation: 41

What is decimal format exactly doing?

This is my code:

float result=(float) ( (new Float(result1)*0.3)+(new Float(result2)*0.7));
String a=dec.format(result);
vprosvasis.setText(a);

If I use vprosvasis somewhere else in my app, it will have the price a.

For example, if my result is 12,34, a will be 12,3 so vprosvasis will be 12,3 if I write

float genikosvathmos = ((new Float(vprosvasis.getText().toString()) +
                         new Float(vprosvasis2.getText().toString()) +
                         new Float(vprosvasis3.getText().toString()) +
                         new Float(vprosvasis4.getText().toString()) +
                         new Float(vprosvasis5.getText().toString()) +
                         new Float(vprosvasis6.getText().toString())) / 6);

Upvotes: 0

Views: 389

Answers (3)

Pops
Pops

Reputation: 30848

Like Daniel, I'm not quite sure what you're trying to get from this post. But I will answer the question you asked in your title at face value.

You don't include the code where dec is declared, or any code where it's operated on, but from context it seems to be an instance of the DecimalFormat class. If so, it's taking result, which is a float, and doing the following things:

  1. widening it to long
  2. using the method format(double number) inherited from NumberFormat to get the String representation of result
  3. storing the result in a

Upvotes: 1

erickson
erickson

Reputation: 269797

The purpose of DecimalFormat is to format numbers as text in a locale-specific way. (It can also be used to parse a locale-specific number format to a suitable Number type.) For example, in the American English locale, a period ('.') is used as a decimal point, rather than a comma (',').

It is important to note that the String produced by a DecimalFormat is very likely to be incompatible with the format required for the Float(String) constructor. The string format consumed by Float is not locale-specific; it is a fixed format that is the same as that specified by the Java Language Specification for float literals in Java source code.

If you are doing calculations with money, don't use a floating-point type like float or double. Use instances of java.math.BigDecimal instead. This type performs exact arithmetic, and when rounding is performed, you can control the rounding to conform with your accounting practices.

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

Would suggest using primitives (specifically, double) rather than Object wrappers (unless you have some need that you're not showing here).

Then look at the Double javadoc, especially the static utility methods:

http://download.oracle.com/javase/6/docs/api/java/lang/Double.html

double myDouble = Double.parseDouble(myString);
String s = Double.toString(myDouble);

Upvotes: 1

Related Questions