Re: yasq
From: Anthony Borla (ajborla_at_bigpond.com)
Date: 01/16/04
- Next message: Michael N. Christoff: "Mars Rover Controlled By Java"
- Previous message: chris: "Re: Deferred Final Automatic Variables"
- In reply to: martin: "yasq"
- Next in thread: hiwa: "Re: yasq"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 16 Jan 2004 21:52:03 GMT
"martin" <nobody@nowhere.org> wrote in message
news:bu97u9$cqg$1@reader11.wxs.nl...
> ... = yet another simple question. ;-))
>
> when I have -for example- a 'double' variable with value
> 231.6847987639475639876478 etc...
>
> How can I have it printed on screen as 231.685 ?
> or as 2.3e+2 ?
>
> in general: How can I set the format in which floats
> (or other var's) are printed on screen?
>
Whilst in some other programming languages use is made of formatting
functions / methods to alter the appearance of output data [but preserve the
original data], in Java the approach is to create an object of the required
format, and simply output that object.
For example, here is a 'float' value:
float f = 5.5789443627326F;
and the desied output appearance is rounded to two decimal places:
5.57
In the C language you would simply do this:
printf("%.2f\n", f);
A suitable representation is created [for internal use] by 'printf', and
output to the console.
On the other hand, in Java you would do this:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String outval = nf.format(f);
System.out.println(outval);
The call to 'nf.format' actually sees a 'String' object created and
returned. In this instance, you have chosen to output this object to the
console. However, since you have this object in your possession, you are
free to use it for other tasks.
If you compare the two approaches, you will see that the C approach is
faster [i.e. you need a single line to generate the required output], but
the Java approach is more flexible [i.e. you have created an object which
can be used for other purposes]. Each approach, also, exemplifies
fundamental idiomatic differences [i.e. ways of doing things] between these
languages. To truly master a language requires that its basic idioms be
understood.
Finally, effective use of Java formatting features requires knowledge of a
number of a number of classes, including:
* Those in the 'java.text' package, including 'NumberFormat'
and 'DecimalFormat'
* 'String', 'StringBuffer'
* The 'type wrapper' classes like 'Float'
I hope this helps.
Anthony Borla
- Next message: Michael N. Christoff: "Mars Rover Controlled By Java"
- Previous message: chris: "Re: Deferred Final Automatic Variables"
- In reply to: martin: "yasq"
- Next in thread: hiwa: "Re: yasq"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|