如何在安卓中获取和设置简单的数学函数?



我正在构建一个简单的电子商务安卓应用程序,我想从给定的实际和交易价格中获得折扣百分比。

这是我的代码:(模型类(

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 变量。

如果您想知道如何计算折扣百分比,可以按如下方式计算。

从原始价格中减去销售价格以确定折扣金额。接下来,将折扣金额除以原始价格。将此十进制金额转换为百分比。此百分比是贴现率。例如,一盏灯显示 30 美元的折扣价,原始价格为 50 美元。$50 - $30 = $20 20/50 = 0.40 0.40 = 40%

或者,如果您不确定将代码放在哪里以及在那里写什么,您可以尝试一下。在您的 NotificationModel 类中有一个方法,该方法将计算并返回折扣百分比。然后,您可以从适配器调用它,如下所示。

discount_percent.setText(notifications.get(position(.discountPercent(((;

您的折扣百分比方法可以如下所示。

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 :- 我已经将actual_price和deal_price解析为整数,假设它们是这样。如果它们可以是浮点数,那么您可能需要将它们解析为浮点数。

最新更新