public class Round {
public static double round(double d) {
int k = 0;
while(d < 0.2) {
d *= 10;
k--;
}
while(d > 2) {
d /= 10;
k++;
}
return (d <= 1 ? 1 : 2) * Math.pow(10,k);
}
public static void main(String... args) {
for(double d : new double[]{0.13, 0.16, 0.91, 1.3, 1.31, 11, 19, 111, 191} ) {
System.out.println("" + d + " -> " + round(d));
}
}
}
...
return (d < 1 ? 0.2 : 1) * Math.pow(10,k);
...
public static final int[] FACTOR =
{1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
/**
* Findet einen Faktor, eine Potenz von 10, mit dem eine Zahl multipliziert v werden
* muss, damit sie größergleich 1 und kleiner 10 ist. Bisher nur im begrenzten
* int-Bereich.
*
* @param value
* @return int
*/
public static double findFactor(double value)
{
if (value <= 0) throw new RuntimException();
double k = Math.log10(_alue);
if (k > 1)
{
int x = (int)Math.ceil(k - 1);
return FACTOR[x];
}
if (k < 0)
{
int x = (int)Math.ceil(-k);
return 1.0 / FACTOR[x];
}
return 1;
}
/**
* Normiert eine Zahl, liefert einfachere Werte in der Nähe, z.B. 20.000 für 19.000,
* 10 für 11 usw.
*
* @param value
* @return int
*/
public static double normalize(double value)
{
double fac = findFactor(value);
// value nun zwischen 1 und 10
value /= fac;
if (value < 1.25)
value = 1;
else if (value < 1.75)
value = 1.5;
else if (value < 2.25)
value = 2;
else if (value < 2.75)
value = 2.5;
else if (value < 3.5)
value = 3;
else if (value < 4.5)
value = 4;
else if (value < 6.25)
value = 5;
else if (value < 8.75)
value = 7.5;
else
value = 10;
value *= fac;
return value;
}
public class Round {
public static double round(double d) {
if(d==0) {
return 0;
}
int k = 0;
double abs = Math.abs(d);
double prefix=d/abs;
//Nur eine Stelle vor dem Komma
while(abs < 1) {
abs *= 10;
k--;
}
while(abs >= 10) {
abs /= 10;
k++;
}
return prefix * Math.ceil(abs) * Math.pow(10,k);
}
public static void main(String... args) {
for(double d : new double[]{-0.13, 0.16, 0.34, 0.91, 1.3, -1.31, 11, 19, 111, 191} ) {
System.out.println("" + d + " -> " + round(d));
}
}
}