Formatting decimal numbers in Java

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
randomtaiwanese
New poster
Posts: 32
Joined: Fri Oct 01, 2004 10:53 pm

Formatting decimal numbers in Java

Post by randomtaiwanese » Tue Nov 16, 2004 11:22 pm

Are there any effective ways of formatting decimal numbers (double) in pascal?
Eg: 3.1245114411 -> 3.12 or 3.125, etc....

User avatar
Sedefcho
A great helper
Posts: 374
Joined: Sun Jan 16, 2005 10:18 pm
Location: Bulgaria

Post by Sedefcho » Fri Jan 28, 2005 6:01 pm

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 ).

User avatar
Sedefcho
A great helper
Posts: 374
Joined: Sun Jan 16, 2005 10:18 pm
Location: Bulgaria

Post by Sedefcho » Fri Jan 28, 2005 7:54 pm

Are you talking about JAVA or Pascal finally?

This is a JAVA forum actually.

tellmewhy
New poster
Posts: 7
Joined: Tue Feb 07, 2006 7:30 pm

Post by tellmewhy » Sat Feb 11, 2006 10:21 am

haha... this is nice joke..... :D
.....Life is just like a LM741........

cksachdev
New poster
Posts: 1
Joined: Mon Sep 25, 2006 4:49 pm

How to in Java 1.3

Post by cksachdev » Mon Sep 25, 2006 4:58 pm

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

Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post by Darko » Tue Sep 26, 2006 4:56 pm

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);
}

otolito
New poster
Posts: 1
Joined: Tue Oct 03, 2006 11:11 pm
Contact:

Is easy

Post by otolito » Tue Oct 03, 2006 11:17 pm

:roll: Check de class NumberFormat.

Post Reply

Return to “Java”