Skip to content

Commit 5677d5c

Browse files
committed
Changes to Strings.autoFixed
1 parent bceaf78 commit 5677d5c

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

arc-core/src/arc/util/Strings.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package arc.util;
22

33
import arc.graphics.*;
4+
import arc.math.*;
45
import arc.struct.*;
56

67
import java.io.*;
@@ -576,9 +577,18 @@ public static float parseFloat(String s, float defaultValue){
576577
}
577578

578579
public static String autoFixed(float value, int max){
579-
int precision = Math.abs((int)(value + 0.0001f) - value) <= 0.0001f ? 0 :
580-
Math.abs((int)(value * 10 + 0.0001f) - value * 10) <= 0.0001f ? 1 : 2;
581-
return fixed(value, Math.min(precision, max));
580+
581+
//truncate extra digits past the max
582+
value = (float)Mathf.floor(value * Mathf.pow(10, max) + 0.001f) / Mathf.pow(10, max);
583+
584+
int precision =
585+
Math.abs(Mathf.floor(value) - value) < 0.0001f ? 0 :
586+
Math.abs(Mathf.floor(value * 10) - value * 10) < 0.0001f ? 1 :
587+
Math.abs(Mathf.floor(value * 100) - value * 100) < 0.0001f ? 2 :
588+
Math.abs(Mathf.floor(value * 1000) - value * 1000) < 0.0001f ? 3 :
589+
4;
590+
591+
return fixed(value, Math.min(max, precision));
582592
}
583593

584594
public static String fixed(float d, int decimalPlaces){

arc-core/test/StringsTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,28 @@
66

77
public class StringsTest{
88

9+
@Test
10+
public void testFixed(){
11+
Object[] values = {
12+
3, 1.327f, "1.327",
13+
2, 1.327f, "1.32",
14+
1, 1.327f, "1.3",
15+
0, 1.327f, "1",
16+
3, 1.3005f, "1.3",
17+
2, 0.0001f, "0",
18+
4, 0.0001f, "0.0001",
19+
3, 0.0001f, "0",
20+
2, 2.435f, "2.43",
21+
2, 2.99f, "2.99",
22+
2, 2.99999f, "3",
23+
2, 0f, "0"
24+
};
25+
26+
for(int i = 0; i < values.length; i += 3){
27+
assertEquals(values[i + 2], Strings.autoFixed((Float)values[i + 1], (Integer)values[i]));
28+
}
29+
}
30+
931
@Test
1032
public void testLongParse(){
1133
Seq.with("0", "+0", "-0", "235235", "99424", "1234", "1", "-24242", "170589", "-289157", "4246", "19284", "-672396", "-42412042040945", "1592835012852095")

0 commit comments

Comments
 (0)