【发布时间】:2021-10-01 17:19:54
【问题描述】:
我想让数字商店类似于电子商务,然后我想将 int 舍入到 Java (Android Studio) 中的下一个最高的 100 倍数,例如:
782->800
9876->9900
7987->8000
24523->24600
123412->123500 等等……
为此,我有一些代码来处理这个问题,但有时我会遇到一些错误,这是我在 java 上的代码
private int fee = 200;
private int getRoundedPrice(int i){
int amount = i + fee;
int roundedAmount = 0;
if(amount < 10000){
roundedAmount = Integer.parseInt(String.valueOf(amount).charAt(0) + "000");
}else if(amount < 100000){
roundedAmount = Integer.parseInt(String.valueOf(amount).substring(0,2) + "000");
}else if(amount < 1000000){
roundedAmount = Integer.parseInt(String.valueOf(amount).substring(0,3) + "000");
}else if(amount < 10000000){
roundedAmount = Integer.parseInt(String.valueOf(amount).substring(0,4) + "000");
}
return roundedAmount + rounding(amount-roundedAmount);
}
private int rounding(int amount){
if(amount < 100){
return 100;
}else if(amount < 200){
return 200;
}else if(amount < 300){
return 300;
}else if(amount < 400){
return 400;
}else if(amount < 500){
return 500;
}else if(amount < 600){
return 600;
}else if(amount < 700){
return 700;
}else if(amount < 800){
return 800;
}else if(amount < 900){
return 900;
}else if(amount < 1000){
return 1000;
}
}
使用此代码,有时它可以工作,但有时这会产生错误,例如:
123141->12400(我经历过)
我不明白问题出在哪里,但我认为这段代码不好(我的意思是不稳定),也许其他人可以帮助我为这个问题提供更好的代码解决方案......谢谢:)
【问题讨论】:
-
显示您尝试过的内容。我们不是来给你写代码的。
-
@Jens 我写了一些代码,我通过删除我显示的代码来编辑我的帖子,我很尴尬地展示它......好吧,我通过显示代码返回了我的帖子,希望你开心,谢谢!
-
这个问题很好。 Stack Overflow 绝对是为像这样描述清楚、重点突出的问题编写代码的。