使用java轻松智能地计算字符串/整数[已关闭]

lf5gs5x2  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(114)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

2天前关闭。
Improve this question
基本上我正在与一个游戏,所以我想要一个简单的方法来确定项目金额。
例如,我正在创建一个ArrayList<Item>();,并标识如下项目:

//Item(itemId, itemAmount);
new Item(ItemsList.COINS, 1_000_000);//this is 1m of coins
new Item(ItemsList.FISH, 2000);//this is 2k of fish

我想要一个更简单的方法而不是把金额写得像

new Item(ItemsList.COINS, Amounts.1M);
new Item(ItemsList.FISH, Amounts.2k);`

像这样,我想就如何创建类金额的指导,并继续下去?
当然,我不打算创建一个枚举与所有的值一样,什么是聪明的方式来完成这项任务。请帮助我,谢谢!

hwazgwia

hwazgwia1#

您可能想尝试这样的方法:

class Amounts {

    public static int k(int amount){
        return amount * 1_000;
    }
    
    public static int M(int amount){
        return amount * 1_000_000;
    }
    
    (...)
}

然后你可以这样使用它:

new Item(ItemList.COINS, Amounts.M(1));
new Item(ItemList.FISH, Amounts.k(2));

但是,我个人更喜欢使用常量(并在三位数后插入_),例如:

new Item(ItemList.COINS, 1_000_000);

或者类似的东西

new Item(ItemList.COINS, 1 * Amounts.MILLION);

(and在类Amounts中定义静态常量public static int MILLION = 1_000_000;

az31mfrm

az31mfrm2#

您可以使用下面的函数将数字转换为您的格式,并可以在您的代码中使用,根据您的要求进行一些更改-

public static String formatNumber(double value) {
    String suf = " kmbt";
    NumberFormat formatter = new DecimalFormat("#,###.#");

    int power = (int)StrictMath.log10(value);
    value = value/(Math.pow(10,(power/3)*3));
    String result =formatter.format(value);
    result  = result  + suf.charAt(power/3);
    return result .length()>4 ?  result .replaceAll("\\.[0-9]+", "") : result ;
}

相关问题