简体   繁体   中英

Is there a way to write a method that outputs the number of digits before the decimal point of a float parameter as a short?

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?

  1. Stick to naming conventions. public static short DigitsBeforeDot(float x){ should be public static short digitsBeforeDot(float x) { or even better: public static short getDigitsBeforeDot(float x) { or public static short calculateDigitsBeforeDot(float x) {

  2. Use a source code formatter if your IDE provides one

  3. Instead of working with float and int , go with double and long . 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.

  4. It's highly unlikely that you want partial/float/fractions of the number of digits (like 2.176 as a result for log10(150) ). It's a lot more likely you want the integer number returned, ie 2 . So you should use an byte/short/int/long as return value. I recommend usnig long : public static long calculateDigitsBeforeDot(double x) { , and instead of casting the log10 to a short , you just cast it to a long instead. Java always rounds towards zero, so that would equal a call to Math.floor(Math.log10(a)) + 1

  5. Why is casting not an option for you?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM