I need to output the total number of digits before the decimal point of a float number and output the results as a short.
This is what I have so far:
public static void main(String[] args) {
DigitsBeforeDot(18.879);
}
public static short DigitsBeforeDot(float x){
short a = (short) x;
System.out.println((short)Math.log10(a) 1);
return a;
}
I get a suggestion to cast the argument in the method to a float like this:
public static void main(String[] args) {
DigitsBeforeDot((float) 18.879);
}
And this makes the program work but I need to make it work without the casting by changing something in the method.
What is the best way to do that?
CodePudding user response:
Stick to naming conventions.
public static short DigitsBeforeDot(float x){should bepublic static short digitsBeforeDot(float x) {or even better:public static short getDigitsBeforeDot(float x) {orpublic static short calculateDigitsBeforeDot(float x) {Use a source code formatter if your IDE provides one
Instead of working with
floatandint, go withdoubleandlong. Apart from storing values in arrays (RAM consumption) there is no downside to using the full register width (64bit) of modern platforms. The upside is that you're a lot less likely to run into problems with precision or overflows.It's highly unlikely that you want partial/float/fractions of the number of digits (like
2.176as a result forlog10(150)). It's a lot more likely you want the integer number returned, i.e.2. So you should use an byte/short/int/long as return value. I recommend usniglong:public static long calculateDigitsBeforeDot(double x) {, and instead of casting the log10 to ashort, you just cast it to alonginstead. Java always rounds towards zero, so that would equal a call toMath.floor(Math.log10(a)) 1Why is casting not an option for you?
CodePudding user response:
Unless I'm missing something, change the signature of the method to take a double.
public static short DigitsBeforeDot(double x) {
short a = (short) (Math.log10(x) 1);
System.out.println(a);
return a;
}
Also, it seems really counter productive to pass a float or a double only to cast to a short.
