how do i trucate a number without using methods like math.round or %3f? AND USING only if statements and cannot use indexOf

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

  •  01-07-2022
  •  | 
  •  

Question

if(number !=(int)number){           
    number*=1000;      
    number=(int)number;  
    number=(double)number; 
    number/=1000;  
    System.out.println("-"+ number);         
}
if(number ==(int)number){       
    System.out.println("-"+ number + "00");
}     

//this part only works if i enter a number that has 3 decimal places or more, I need 1 decimal place or 2 decimal place to work ex: (12.1 I need it to display 12.100) or (12.11 to display 12.110)

Was it helpful?

Solution

If printing it is the only thing that's required, this should work. If you require returning a value, you can always store it as a string.

public static void myFormat(double number){
    String sign = "";
    if (number < 0) { sign = "-";}

    int decimalPart, wholePart;

    if(number == (int)number){ // number is an integer
        System.out.println( (int)number+".000");
    }
    else { // number has some decimal components
        int myNewNum = (int)(number * 1000); // get the portions we need
        decimalPart = myNewNum - ( (int)number * 1000 );
        wholePart = (myNewNum - decimalPart) / 1000;

        //make whole and decimal part positive for formatting purposes
        if (decimalPart < 0) { decimalPart *= -1; }    
        if (wholePart < 0) { wholePart *= -1;}

        System.out.println(sign + wholePart + "." + decimalPart);
    }
}

This is based on the assumption that you cannot use any external library or methods. It is verbose, but the mathematics is correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top