gpt4 book ai didi

Java 带极性的百分比差异逻辑

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:32 25 4
gpt4 key购买 nike

我正在尝试创建两个值之间的百分比差异 - 我需要 a) 确保显示的值正确 - 例如 +35%、250%、-25% b) 破译它是正变化还是负变化。

enter image description here

float thisPeriod = 10;
float lastPeriod = 8;

float percentage = (float) (thisPeriod/lastPeriod) * 100;
System.out.println("percentage " + percentage);

String polarity = BasicUtils.checkPolarity(percentage);
System.out.println("polarity " + polarity);


public static String checkPolarity(float difference){
if(difference == 100) return "positive";

if(difference < 100){
return "negative";
}else {
return "positive";
}
}

-- 场景 1本期 - 10 名成员上期 - 8 名成员

So there is a +25% difference. (125-100?)

-- 场景 2本期 - 20 名成员上期 - 15 名成员

So there is a 33% difference. (133-100?)

-- 场景 3本期 - 20 名成员上期 - 10 名成员

So there is a +200% difference. -- but then shouldn't this be 100% difference (200-100?)

-- 场景 4本期 - 40 名成员上期 - 10 名成员

So there is a +400% difference. -- but then shouldn't this be 300% difference (400-100?)

---我在这里获得这种显示的逻辑是否正确?

最佳答案

你的逻辑好像有点不对劲。如果您想要相对于先前值的百分比变化,我认为它应该是 difference/old_value:

public static String percentageChange(double last, double now) {
double delta = now - last;
double change = delta / last;
return String.format("%+.2f%%", change * 100);
}

示例:

percentageChange( 8, 10);    // +25.00%
percentageChange(15, 10); // -33.33%
percentageChange(10, 30); // +200.00%

关于Java 带极性的百分比差异逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com