Java String "1603" to float 16.03 - java

So I have some java Strings of variable length. It can be from 0 to 999999999 but the last two values should always become the decimal part. I want to convert those strings to float values.
The way I was thinking about was:
String strNum = "200";
strNum = strNum.substring(0, strNum.length()-2) + "." + strNum.substring(str.length()-2);
Float num = Float.parseFloat(strNum);
But this method is quite slow, and I should also add some way to look if the length is bigger than 2, to avoid string index out of range.
My question is: is there any way of doing this in a cleaner and faster way? Otherwise I'll do it as I've been thinking.
Thanks

How about:
float num = Integer.parseInt(strNum) / 100f;
The f after 100 is important, and unless needed, use float, not Float.

String substring function is costly as it creates new Object.So its better to first convert it into number and then divide by 100 to get the desired output.
float num = Integer.parseInt(strNum) / 100f;

If you're sure your string will always be digits only what about a nice simple
float num2 = Float.valueOf(strNum)/100;
Hmm, I type too slow! :)

Related

Double with custom quantity zero's after dot

I have two Integer values and I need create Double value from combining this two values in following way:
A.CB
where:
A — first integer value
B — second integer value
C — zero's to match total length
Basically, CB is always have to be 9 digits in total, that's mean when B = 1 I need that C will be 8 zero's, if B=100 I need C will be 6 zero's.
To get this results:
15.000000001
and
17.000000100
What is the best way to approach this logic in code? I mean I can write custom method to create this logic, but is Java already have something for this case to just use it, without creating custom methods? Better if it's possible without using string format functions (to not convert Integer values to String).
Something like this?
int A = 123, B = 450;
System.out.println(String.format("%.09f", A + 1e-9 * B));
Will print
123.000000450
P.S. String.format is required because of your trailing-zeros-after-the-comma requirement. Those zeros don't actually exist, so you need some way to pad your output, and String.format is a convenient way to do that. If you just want a double value, you don't need String.format.
Divide b / 1000000000.0:
int a = 12;
int b = 123;
double x = a + b / 1000000000.0;
System.out.println(x);
Will print:
12.000000123
Unless b's length is longer than 9 digits, you will get what you want.
int a = 12;
int b = 123;
// How many digits in b?
int blen = (int)Math.log10(b);
// Make a string of zeros
String padding = "00000000".substring(blen);
System.out.println(a + "." + padding + b);
This will fail apart if b is very large, as blen will be larger than the padding, and so substring will fail. Also, negative b will mess things up.

How to convert a float to int along with its decimals considered?

For example, I am having 12.12 float value I want it to become 1212 an integer value
If I am having 156.2345 I want it to be 1562345.
I have searched a lot but found only rounding and casting to int but no answer for my question.
Moreover, if we have 12.12000 then also I should be getting 1212 only but not 1212000.
The problem is I will be reading double or float from stdinput and I have to convert that to appropriate int as per above rules
Tried Float.intValue() among others, but that gives 12 only
Use following:
floatValue.toString().replaceAll("[0]*$", "").replace(".", "");
First replace will remove all trailing 0s from the float value while second replace will remove the dot.
I am not sure it's a good idea to do this but you can do
double d = 12.12;
long n = Long.parseLong(BigDecimal.valueOf(d).toString().replaceAll("[.,]", ""));
This will drop any decimal places. You can use float and int instead.
If you want 1.0 to be 1 instead of 10, and 10.0 to be 1 instead of 10or 100 you can add
.replaceAll("[0]*$", "")
Tried Float.intValue() among others, But that gives 12 only
As it should. intValue returns the value as an int rounded down.
Here's an alternative approach that multiplies the number by 10 until the remainder division by 1 yields 0:
static long toLong(double d) {
if (d % 1 != 0) {
return toLong(d * 10);
}
return (long) d;
}
Integer.parseInt(Float.toString(value).replaceAll(Pattern.quote("."), ""));
The shortest and safe code.
replaceAll() takes regex as argument, so you must use Pattern.quote();
Integer.parseInt(): Parses an Integer from String. (ex: "123" -> (int)123)
Float.toString(): Converts a Float to String. (ex: 12.34 -> "1234")
replaceAll(String regex, String change_to): Replace all 'regex' to change_to.

Finding number of digits before a decimal point in java

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);

How to cast String with decimal(a.bc) to int(abc) in Java

I want to do some calculation with a list of String:
1.23
4.56
7.89
For accuracy, I want the convert the above String to int:
123
456
789
How to do that?
Sorry for my vague description. What I really need is no matter what the input is, the int value should hold the specific decimal:
Let say I need 4 decimal:
String:1 ; int: 10000
String:1.23 int: 12300
String:1.2345 int:12345
I would strip out the dots then parse as an int:
int i = Integer.parseInt(str.replace(".", ""));
If you need there to always be 3 digits, this approach gets ugly, but doable:
int i = Integer.parseInt((str.replace(".", "") + "00").replaceAll("^(...).*", "$1"));
This avoids the vagaries of the imprecision of double values, which could lead to incorrect results due to truncation when casting from double to int.
Here's an example of imprecision problems:
int i = (int) (100 * Double.parseDouble("1.13")); // 112
This is because:
double d = Double.parseDouble("1.13"); // 112.99999999999999
You can use
long n = Math.round(Double.parseDouble(text) * 100);
This will mean numbers like 0.1 will be 10 not 1 and 1.110 will be 111 not 1110
Let say I need 4 decimal:
String:1 ; int: 10000
String:1.23 int: 12300
String:1.2345 int:12345
needs
long n = Math.round(Double.parseDouble(text) * 10000);
You can replace all dots with empty strings (text.replace(".", "")) and then use Integer.parseInt(text).
For one String, you can do:
private static final BigDecimal ONE_HUNDRED
= new BigDecimal(100);
// In code:
new BigDecimal(inputString).multiply(ONE_HUNDRED).intValueExact();
Note the use of BigDecimal here; a double will NOT do.
Note also that it will work only if the input has at most two decimal digits: if more than that, .intValueExact() will throw an exception (it will also throw an exception if the decimal integer is out of bounds for an int).
Now, it depends on how precise you need to be; this method guarantees the results. The method to remove dots and parse as int is obviously faster ;)
I will suggest you use string.replace and replace all "." with "". Then you can use Integer.parseInt(str) and you will have the result.
str = str.replace(".", "");
int val = Integer.parseInt(str);

String trim coming out with incorrect length

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());

Categories

Resources