Page 1 of 1

Formatting decimal numbers in Java

Posted: Tue Nov 16, 2004 11:22 pm
by randomtaiwanese
Are there any effective ways of formatting decimal numbers (double) in pascal?
Eg: 3.1245114411 -> 3.12 or 3.125, etc....

Posted: Fri Jan 28, 2005 6:01 pm
by Sedefcho
I do it this manually ( on my own ) .

Say you have a double X and you want to round it to
2 decimal digits after the dot sign.

double X = <some value>;

For Example you want
if X = 35.12350 -> round -> 35.12
if X = 35.12450 -> round -> 35.12
if X = 35.12550 -> round -> 35.13
if X = 35.12650 -> round -> 35.13

You can do this:

int p = (int)(x * 1000) ;

if (p % 10 >= 5 ) {
p = p + 10;
}

p = p / 10;

String digitsAfterDot = ( ( p % 100 ) + "" ) ;
String digitsBeforeDot = ( ( p / 100 ) + "" );

Not you just print the two String objects you have.


You can do the same if you want to use different rounding
( say to 3 or 4 digits after the decimal point ).

Posted: Fri Jan 28, 2005 7:54 pm
by Sedefcho
Are you talking about JAVA or Pascal finally?

This is a JAVA forum actually.

Posted: Sat Feb 11, 2006 10:21 am
by tellmewhy
haha... this is nice joke..... :D

How to in Java 1.3

Posted: Mon Sep 25, 2006 4:58 pm
by cksachdev
Please tell me how do I can implement it if I don't know the number of places after '.'
I have to implement it in Java

Please post

Posted: Tue Sep 26, 2006 4:56 pm
by Darko
I use this (works for me):

Code: Select all

private String fmt(double d, int prec) {
	long pow10 = 1;
	for (int i = 0; i < prec; i++) {
		pow10 *= 10;
	}
	long l = Math.round(pow10 * d);
	String sign = "";
	if (l < 0) {
		sign = "-";
		l = - l;
	}
	String s = Long.toString(l);
	int len = s.length();
	for (int i = 0; i < prec + 1 - len; i++) {
		s = "0" + s;
	}
	len = s.length();
	return sign + s.substring(0, len - prec) + "."
			+ s.substring(len - prec);
}

Is easy

Posted: Tue Oct 03, 2006 11:17 pm
by otolito
:roll: Check de class NumberFormat.