gpt4 book ai didi

java - 漂亮的数字格式化算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:11 28 4
gpt4 key购买 nike

将表示多个字节的整数转换为漂亮格式的算法。最多 3 位数字(不包括小数点)- 例如像 linux 命令行。没有前导或尾随零1K是1000字节

Examples:
Correct
123B -> 123B
12300B -> 12.3K
1910000B -> 1.91M
1000000000B -> 1G
83123 = 83.1K (not 83K)

Incorrect
012K (should be 12K)
8.20M (should be 8.2M)

我想知道我做错了什么,或者是否有更好的简单方法来解决这个问题,或者我的代码中是否存在任何错误。

下面是我的解决方案(它有效但我没有被选中所以我不知道我做错了什么)-

/*
* @Description - Function takes integer as input and returns the number in
* pretty format(Gigabyte, Megabytes, KiloBytes, Bytes) with maximum of 3
* digits
* @param integer to convert to pretty format
* @Assumptions - As mentioned in the problem set, 1000bytes = 1KB
* Value is rounded to the nearest valid value
* In java leading 0 in number is considered Octal, this function does not
* take care of octal to decimal conversion
* As 1G = 1,000,000,000B the loop will run maximum 3 times in worst case
* Its requires constant space O(1) to store the result
*/
static String fpretty(int num) {

int count = 0;
double div_result = (double) num;
String display = "";

/*
* Every time we divide by 1000 count is incremented from B->K->M->G
* Here two decimal places are preserved for cases like 1.05, 1.11
* The output result of this loop will have 1,2 or 3 digits with max
* two decimal places
*/
while(div_result > 999.5) {
div_result = div_result / 1000;
div_result = Math.round(div_result * 100.0) / 100.0;
count++;
}

// Get suffix B, K, M or G
String measure = getUnit(count);

// If decimal places is all zeros OR result has 3 digits
if(div_result % 1 == 0 || div_result >= 100)
display = (int)div_result + measure;
// If result has 2 digits
else if (div_result >= 10) {
// Then fetch 1 decimal place as we have 2 digits
div_result = (Math.round(div_result * 10.0) / 10.0);
// If after rounding decimal places are .0 then truncate zeros
// eg. 99.97 rounded to -> 100.0 -> 100
if(div_result % 1 == 0)
display = (int)div_result + measure;
else
display = div_result + measure;
}
else
display = div_result + measure;

return display;
}

最佳答案

使用 DecimalFormat 可以轻松完成此操作类(class)。让它为你做四舍五入,可以用一个模式来描述,通过RoundingMode选择四舍五入的方式。 .它还会处理尾随零,这些零将被简单地忽略。

public String pretty(int num) {
DecimalFormat f = new DecimalFormat("###.##");
f.setRoundingMode(RoundingMode.HALF_UP);
double prettyd = num;
int count = 0;
while (prettyd >= 1000.0) {
prettyd /= 1000.0;
count++;
}
return f.format(prettyd) + getUnit(count);
}

关于java - 漂亮的数字格式化算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791086/

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