Reputation: 55
I want my code to take out 0's and put M,B,T ect. after 1,10,or 100, but I don't know how to do it.Basically The program is asking how much money you want like you would put 10000000000. Then kb gets that int, And int b gets length of a, but this is where I have a problem because I can't find a way to make the 10000000000 into 10, and then have it print 'You have $10T',
public class MinersHavenMoney_Client
{
private final static String filename = "input.txt";
public static void main(String[] args) throws FileNotFoundException {
int x;
Scanner kb = new Scanner(System.in);
MinersHavenMoney m1;
m1 = new MinersHavenMoney();
System.out.println("How much money do you want");
int a = kb.nextInt();
int b = String.valueOf(a).length();
kb.close();
if(b<=6)
System.out.println("You have $" + a);
else if(b>=7&&b<=9)
System.out.println("You have $" + c + "M");
else if(b>9&&b<=12)
System.out.println("You have $" + a + "B");
else if(b>12&&b<=15)
System.out.println("You have $" + a + "T");
//There is more but there is to much
}
}
Upvotes: 1
Views: 67
Reputation: 201447
First you'll need a long
to support values into trillions (int
has the range -231 to 231-1). Then you could use a regular expression. If the number ends in 12 0s it is trillions, 9 0s it is billions, 6 0s for millions and 3 0s for thousands. Something like,
long b = 10L * 1000 * 1000 * 1000 * 1000;
System.out.println(String.valueOf(b).replaceAll("[0]{12}$", "T")
.replaceAll("[0]{9}$", "B").replaceAll("[0]{6}$", "M")
.replaceAll("[0]{3}$", "K"));
Outputs (as requested)
10T
Upvotes: 2
Reputation: 533520
Instead of comparing the number of digits, you can compare the values.
public static String scale(double value) {
return value < 1e3 ? asText(value) :
value < 1e6 ? asText(value / 1e3) + "K" :
value < 1e9 ? asText(value / 1e6) + "M" :
value < 1e12 ? asText(value / 1e9) + "B" :
asText(value / 1e12) + "T";
}
public static String asText(double d) {
return (long) d == d ? Long.toString((long) d) : Double.toString(d);
}
Upvotes: 4