How do i find the right most digit of a number integer with java without using number % 10? see the description

StackOverflow https://stackoverflow.com/questions/19737138

  •  03-07-2022
  •  | 
  •  

Frage

Right now I'm using something like this: Basically the program is supposed to print X (right most digit of a #) to X decimal places for example:

  • entered 3.56, should display 0000000000000003.560
  • entered 56.7 should display: 000000000056.700000
  • entering 1002.5 should display 00000000000001002.50

but number % 10,condition right now only accepts number w/o decimals, so the program closes if i enter a number with decimals I only need an alternative for number % 10.

double number;
if (number % 10 == 1)
System.out.printf("%020.1f\n",number);
War es hilfreich?

Lösung

It seems that you are looking for something like

System.out.printf("%020." + ((int) number) % 10 + "f\n", number);

((int) number) will get rid of fraction making 56.7 -> 56, so now you can safely use %10 to get last digit.

DEMO

Andere Tipps

If I have interpreted your question correctly then this looks like it does what you ask:

public void test() {
  strangePrint(3.1415);
  strangePrint(2.0);
  strangePrint(2.1);
  strangePrint(2.2);
  strangePrint(2.999);
  strangePrint(37.4);
  strangePrint(3.56);
  strangePrint(56.7);
  strangePrint(1002.5);
}

private void strangePrint(double d) {
  // Get the integer part
  int n = (int)d;
  // The last digit of the integer defines the decimal places.
  int digits = n%10;
  System.out.printf("%020."+digits+"f\n", d);
}

prints

0000000000000003.142
00000000000000002.00
00000000000000002.10
00000000000000002.20
00000000000000003.00
000000000037.4000000
0000000000000003.560
0000000000056.700000
00000000000001002.50

From number in format:

ABCDEX.FGHI

you can extract X by:

int x = (int) original; //get rid of what is after the decimal point
//now x is ABCDEX
x = x % 10;
//now x is X

now you can join this int with string to create pattern for printf.

Based off of your original post, it seemed like you weren't allowed to use mod, so here's how I would do it:

private void transform(Double number)
{
    int result;
    int x = number.intValue();

    if (x < 10)
    {
        result = x;
    }
    else
    {
        Double y = x / 10.0;
        int z = y.intValue();
        result = x-10*z;
    }

    System.out.printf("%020." + result + "f\n", number);
}

Test runs:

transform(3.56);
transform(56.7);
transform(1002.5);  

Prints:

0000000000000003.560
0000000000056.700000
00000000000001002.50

EDIT:
If I misinterpreted and you are allowed to use mod, then the answer is simply:

private void transform(Double number)
{ 
     System.out.printf("%020." + ((int) number) % 10 + "f\n", number);
}

as others have suggested. Sorry if I misunderstood.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top