I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000, but instead it return the place value of whatever length is. So, for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760 then it would return 5000. I hope that makes sense. Any suggestions would be much appreicated.
CodePudding user response:
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4)
-> 50000
roundDown(46287,3)
-> 46000
roundDown(65478,2)
-> 65400
roundDown(43298,1)
-> 43290
roundDown(43278,0)
-> 43278
CodePudding user response:
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers) I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N "";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i ) // pad following digitals
rtn ="0";
return Integer.parseInt(rtn);
}
CodePudding user response:
I appreciate you asked the question here. Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length counts the length.
length ;
temp1*=10;
}
for (int i=1; i<length; i ){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.