我正在构建一个简单的电子商务 Android 应用程序。我想从给定的实际价格和交易价格中获取折扣百分比。
这是我的代码:(模型类)
String actual_price;
String deal_price;
public NotificationModel(String actual_price, String deal_price) {
this.actual_price = actual_price;
this.deal_price = deal_price;
}
public String getActual_price() {
return actual_price;
}
public void setActual_price(String actual_price) {
this.actual_price = actual_price;
}
public String getDeal_price() {
return deal_price;
}
public void setDeal_price(String deal_price) {
this.deal_price = deal_price;
}
适配器类:
public TextView actual_price;
public TextView deal_price;
public TextView discount_percent;
actual_price = (TextView) mView.findViewById(R.id.just_in_actual_price);
deal_price = (TextView) mView.findViewById(R.id.just_in_deal_price);
discount_percent = (TextView) mView.findViewById(R.id.apv_discount);
if (TextUtils.isEmpty(notifications.get(position).getActual_price())) {
holder.actual_price.setText("Not Available");
} else {
holder.actual_price.setText("₹" + notifications.get(position).getActual_price());
}
if (TextUtils.isEmpty(notifications.get(position).getDeal_price())) {
holder.deal_price.setText("Not Available");
} else {
holder.deal_price.setText("₹" + notifications.get(position).getDeal_price());
}
不明白要编写什么代码才能获得折扣百分比。并将其设置为discount_percent变量。
最佳答案
如果您想知道如何计算折扣百分比,可以按如下方式计算。
Subtract sale price from original price to determine the discount amount. Next, divide the discount amount by original price. Convert this decimal amount into a percentage. This percent is the discount rate. For an example, a lamp shows a discount price of $30 with an original price of $50. $50 - $30 = $20 20 / 50 = 0.40 0.40 = 40%
或者,如果您不确定将代码放在哪里以及在那里写什么,您可以尝试这个。在您的NotificationModel类中有一个方法可以计算并返回折扣百分比。然后您可以从适配器中调用它,如下所示。
discount_percent.setText(notifications.get(position).discountPercentage());
您的discountPercentage 方法可以如下所示。
public String discountPercentage() {
int actualPrice, dealPrice;
try {
actualPrice = Integer.parseInt(actual_price);
dealPrice = Integer.parseInt(deal_price);
} catch (NumberFormatException ex) {
return "Not Available";
}
int discount = actualPrice - dealPrice;
float discountPercentage = ( (float) discount / actualPrice ) * 100;
return String.format("%.02f", discountPercentage) + "%";
}
PS:- 我已将实际价格和交易价格解析为整数,假设它们是这样。如果它们可能是 float 的,那么您可能需要将它们解析为 float 。
关于java - 如何在android中获取和设置简单的数学函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58309864/