Are there any effective ways of formatting decimal numbers (double) in pascal?
Eg: 3.1245114411 -> 3.12 or 3.125, etc....
Formatting decimal numbers in Java
Moderator: Board moderators
-
- New poster
- Posts: 32
- Joined: Fri Oct 01, 2004 10:53 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 ).
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 ).
How to in Java 1.3
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
I have to implement it in Java
Please post
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
![:roll:](./images/smilies/icon_rolleyes.gif)