I am using Java to determine the length of a double as part of a larger program. At this time the double is 666 but the length is returning as 5, which is a big problem. I read another question posted here with a solution but that didn't work for me. I will show my code and my attempt at emulating the previous solution with results.
My original code:
double Real = 666;
int lengthTest = String.valueOf(Real).trim().length();
System.out.println("Test: " + lengthTest);
This prints 5
Modifications that didn't work, and were essentially just breaking up the code into multiple lines.
double Real = 666;
String part = Real + "";
part = part.trim();
int newLength = part.length();
System.out.println("new length : " + newLength);
This prints 5 as well.
Obviously, I want this to print how many digits I have, in this case it should show 3.
For a bigger picture if it helps I am breaking down number input into constituent parts, and making sure none of them exceed limits. ie: xx.yyezz where xx can be 5 digits, yy can be 5 digits and zz can be 2 digits. Thank you.
That's because you are using a double.
String.valueOf(Real); // returns 666.0, i.e. length 5
Try casting it to an integer first:
Integer simple = (int) Real;
String.valueOf(simple); // returns 666, i.e. length 3.
A double always puts a decimal place after the number. So the number looks like 666.0. You could see this by printing String.valueOf(Real). You should use an int instead or cast the double to an int:
double Real = 666;
int realInt = (int) Real;
System.out.println(String.valueOf(realInt).length());
Related
I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.
The two values that i have are:
firstval=200.000
Secondval=399.999,
I have to generate a numbers such that when the first decimal part should get incremented till 999 for the integral part, next the integral part should be incremented and then decimal part resets to 000 and starts incrementing for the new number . And this happens till 399.
Like
200.001,200.002.....200.999,201.000,201.002....399.998,399.999"
There is a nice way to get required array with Java 8 Stream API
(1) Use double incrementation
double[] sequence = DoubleStream.iterate(200.0, d -> d + 0.001).limit((int) (1 + (399.999 - 200.0) / 0.001)).toArray();
Note, that summing up lots of doubles will likely give some error, for example on my laptop the last number in the sequence is 399.99899999686227
(2) Better way is to generate integer stream and map it to doubles:
double[] sequence = IntStream.range(200000, 400000).mapToDouble( i -> i * 0.001).toArray();
In this case no error from adding multiple doubles will be accumulated
double start = 200.0;
double end = 399.999;
double increment = 0.001;
for (double v = start; v < end + increment / 2; v += increment) {
System.out.printf("%.3f\n", v);
}
Here's another way to do it:
public static void counterGenerator(double start, double end) {
DecimalFormat counterInDecimalFormat = new DecimalFormat("0.000");
String counterInString = counterInDecimalFormat.format(start);
System.out.println(counterInString); // This is the counter in String format.
double counter = Double.parseDouble(counterInString);
if (counter < end)
counterGenerator(start + 0.001, end);
return;
}
In the above example, you have your counter in String format in the variable called counterInString
But you need not worry about the problems associated with incrementing a Double which is actual residing in a String variable. In the code, you can see the incrementing task is being done by a double counter which gets convert back to String by using the DecimalFormat class.
Here keeping your counter as a String helps you to retain the 0s after decimal in numbers like 200.000.
Hope it helps!
I have declared the variable for the double I'm using:
z= 345.876;
Now I want to display the number of digits that come before the decimal point. I tried to do the following:
String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
I get an error saying: 'The method subString(int, int) is undefined for the type String'
Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?
And also how would I modify that to find the number of digits that come after a number? I know in the part
.indexOf('.')
I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.
You're trying to use string_form before you have actually created it.
If you break
String string_form = new Double(z).toString().substring(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
into
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(0,string_temp.indexOf('.'));
double t = Double.valueOf(string_form);
Then it should work.
To get the numbers after the decimal point just take the digits from period until the end of the number.
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(string_temp.indexOf('.'), string_temp.length());
double t = Double.valueOf(string_form);
As others have pointed out though, there are many better ways than converting to string and checking for period and reconverting.
The number of decimal digits before the decimal point is given by
(int)Math.log10(z)+1
The number of decimal digits after it is imprecise and depends on how much precision you use when converting to decimal. Floating-point values don't have decimal places, they have binary places, and the two are incommensurable.
just convert the double to a string. find the index of . with indexOf. get the length of the string. subtract the index of . from the length and you should have the count.
String string_form = Double(z).toString();
int index = string_form.indexOf('.');
double d = Double.parse(string_form.substring(0, index+1));
If the numbers are small, you could try
int i = (int) z;
or
long l = Math.round(z);
You're using string_form in the expression string_form.indexOf('.'), but it's not initialized yet, because it's only set after the call to substring(). You need to store the value of toString() in a temporary variable so you can access it in the call to substring(). Something like this
String stringForm = new Double(z).toString();
stringForm = stringForm.substring(stringForm.indexOf('.'));
There are other and better ways to do this, however. Math.floor(z) or even just a cast (long)z will work.
Could do this, for examble:
Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);
You can do the next thing:
Double z = 345.876;
int a = t.intValue();
int counter = 0;
while(a != 0) {
counter++;
a = a / 10; }
System.out.println(counter);
I am having some trouble with some extra credit stuff my AP Computer Science teacher assigned. Here are the instructions:
Write a WordScrambler method recombine. This method returns a String created from its two String parameters as follows:
take the first half of word1
take the second half of word2
concatenate the two halves and return the new string
For example, the following lines show some results of calling recombine. Note that if a word has an odd number of letters, the second half of the word contains the extra letter.
here are the examples it gives:
"apple" + "pear" = "apar"
"pear" + "apple" = "peple"
it then says to create method recombine below, only giving one line of code:
private String recombine(String word1, String word2)
then I have to create the rest. I made a test program just to see if my ideas were correct, that I could use length() and substring() to do it (I know I will have to use them some time in it), then I would change the code to work with the private String recombine(word1,word2) bit. So here is my test code:
public class test
{
private static String word1,word2;
public static void main(String[]args){
word1 = "apple";
word2 = "pear";
int length1 = word1.length();
int length2 = word2.length();
System.out.println(length1);
System.out.println(length2);
int half1 = (int)Math.ceil(length1 / 2);
int half2 = length2 / 2;
System.out.println(half1);
System.out.println(half2);
}
}
the output is:
5
4
2
2
As you can see, the variable half1 should be 2.5, but since you cant use half of a letter, it should round up, but even with (int)Math.ceil it still rounds down. When I take out the int, just to see if it works as a double, it gives me an error, 'Possible loss of precision, required:int; found:double;`
The general answer to your question, for the quotient of two positive numbers a and b, is to compute(*) (a + b - 1) / b with the truncating division that most programming languages have. This produces the integer immediately above the real a / b.
In your example, b is 2. The value of length1 / 2 rounded up can be computed as (length1 + 1) / 2.
(*) This is assuming that a + b - 1 can be computed without overflow, which should not be a problem in your example.
The reason your code does not round down is that the division length1 / 2 happens before Math.ceil call, and it happens in integers.
You can round up division without using Math.ceil. For that you add a number that is less than the divisor by one to the number being divided. For example, if you want to round up the result of division by ten, add nine to the dividend:
int res = (d + 9) / 10; // Rounds up
In your case, all you need is to add one to length1:
int half1 = (length1+1) / 2;
The immediate solution is just to do the division in floating point:
int half1 = (int)Math.ceil(length1 / 2.0);
2 is an int literal and 2.0 is a double literal. Java will automatically promote length1 to double in the presence of 2.0 so this is effectively the following:
int half1 = (int)Math.ceil((double)length1 / 2.0);
But as noted by the other two answers, you don't need to use floating point. Furthermore, double only has 53 bits of integral precision so while doing the division in floating point works for an int it may result in error for a long.
I am wanting to store an integer named Amount, I want it to be stored in pence so if the user entered 11.45 it would be stored as 1145. What is the best way to remove the decimal point? Should I be using decimalFormatting in Java?
Edit:
It is entered in string format, was going to covert it to an int. I will give one of your solutions ago and let you know if it works but not sure which one would be the best.. Thanks everyone.
times it by 100 and cast as int. Use decimal formatting is double / float are too inaccurate which they may be for money
If the user input is in the form of a string (and the format has been verified), then you can strip out the decimal point and interpret the result as an integer (or leave it as a string without the decimal point).
String input = "11.45";
String stripped = input.replace(".", ""); // becomes "1145"
int value = Integer.parseInt(stripped);
If it's a float already, then just multiply by 100 and cast, as #user1281385 suggests.
What about convert to float, multiply by 100 and then convert to int?
String pound = "10.45"; // user-entered string
int pence = (int)Math.round(Float.parseFloat(pound) * 100);
This might be also useful: Best way to parseDouble with comma as decimal separator?
Tested and works. Even if the user enters a number without a decimal, it will keep it as such.
double x = 11.45; // number inputted
String s = String.valueOf(x); // String value of the number inputted
int index = s.indexOf("."); // find where the decimal is located
int amount = (int)x; // intialize it to be the number inputted, in case its an int
if (amount != x) // if the number inputted isn't an int (contains decimal)
// multiply it by 10 ^ (the number of digits after the decimal place)
amount = (int)(x * Math.pow(10,(s.length() - 1 - index)));
System.out.print(amount); // output is 1145
// if x was 11.4500, the output is 1145 as well
// if x was 114500, the output is 114500