Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.
I tried many things:
1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
2) a = 3.14;
a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001
converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
split uses a regex, so you have to escape the dot.
string.split(".")
should become
string.split("\\.")
With this you should be able to split the string properly and do your comparisons
By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.
You could separate the fractional part for comparison instead
double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see
why you're seeing additional digits after your own numerical operation
your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)
Try this out
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float v1 = 3.13f,v2 = 4.13f;
//Converting float value into String array
String split1[]=Float.toString(v1).split("\\.");
String split2[]=Float.toString(v2).split("\\.");
//Comparing two strings
if(split1[1].equals(split2[1]))
{
System.out.println("Yes");
}
}
}
Related
I want to ask how to transform all my String to double with exponential.
when I use the string that length is over seven it's doing fine .
new BigDecimal("12345678").doubleValue() => 1.2345678E7
but seven and under I can't export exponential number.
new BigDecimal("1234567").doubleValue() => 1234567.0
what I want is like 1.234567E6.
Is there any way to do this? I've been searching for a while ,but got nothing.
The problem is the type I return must be double . After transforming the value under seven I can only get the value without exponential.
double test = new BigDecimal("1.234567E6").doubleValue() ;//output 1234567.0
but I need it to be 1.234567E6 and return to caller. Is that Impossible?
You should know that 1.2345678e7 and 12345678.0 are exactly the same value, only with different textual representations. You could represent 1234567.0 as 1.234567e6 too. Also exactly the same double, just a different way of writing it out.
The default output shows values with more than a certain number of significant digits in exponential format ("e-form"), otherwise as plain decimal format.
So you may want to change the formatting of the doubles you receive. This can be done with e.g. DecimalFormat or String.format() or similar. That does not change the doubles, only the way they are presented in a string.
For your problem, you want to convert the value to the BigDecimal with exponential, you can use the DecimalFormat. You can also change the scale for the output value digits.
import java.math.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
double a = new BigDecimal("1234567").doubleValue();
String b;
System.out.println(a);
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.DOWN);
formatter.setMinimumFractionDigits(5); //<---Scale
b = formatter.format(a);
System.out.println(b);
}
}
The output will be like:
1234567.0 //Unformatted Value
1.23456E6 //Formatted Value
See the section about Scientific Notation in java.text.DecimalFormat.
For example,
DecimalFormat scientificFormat = new DecimalFormat("0.###E0");
System.out.println(scientificFormat.format(BigDecimal.valueOf(123456L)));
System.out.println(scientificFormat.format(BigDecimal.valueOf(1234567L)));
scientificFormat.setMinimumFractionDigits(10);
System.out.println(scientificFormat.format(BigDecimal.valueOf(12345678L)));
would give you
1,235E5
1,235E6
1,2345678000E7
Change the pattern to match what you're looking for.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.
I am in a COMP 110 class which is intro to Java. This specific program is irrelevant to the class but to help my own understanding with Java.
I believe I have imported the tool to allow the program to calculate basic math operations by using "java.lang.Math;"
I understand * is multiplication, / is division, + is addition, - is subtraction, and % finds the remainder.
The final line of the program gives me the error message:
squared.java:14: operator * cannot be applied to java.lang.String,java.lang.String
and I am at a loss for why because I have imported the language Math, which should enable me to use the * to multiply the value variable when I enter "value * value"
import java.util.Scanner;
import java.lang.Math;
public class squared {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
String value = number.nextLine();
System.out.println("The square of the number" + value + "is" + value * value);
}
}
Yes you must first convert it into an Integer, Double, Float, etc in order to do a multiplication on such. So just do
int v = Integer.parseInt(value.trim());
Then
System.out.println("The square of the number"+v+"is"+ (v * v));
Also using operators has nothing to do with Math library. Math library is used like so:
double d = Double.parseDouble(value.trim());
Math.pow(d,2.0); //which does the same thing above
There are two approaches to go about this program -
1) Read the input as String and then convert it to int or
2) Read the input as int(or double?) itself.
Following code shows how you can read the input as int and perform the operation.
Note the code change (value*value) in your sysout statement. When you concatenate any value to a string, it get treated as string, and hence you are getting the error. Put it in parenthesis such that before concatenating, actual value*value operation is performed.
public class squared {
public static void main(String[] args){
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
int value = number.nextInt();
System.out.println("The square of the number"+value+"is"+ (value * value));
}
}
Talking about Math.pow(), it doesn't serve any different purpose here. Using it is same as the way you have done here.
First of all, you don't need to import java.lang.Math. All of the java.lang libraries are already there. Also, you don't need to use the Math library for operations. You use it for things like Math.sin() to find the sine of an angle, or Math.pow() to get the power of one number to another. If you want a full list of the uses for java.lang.Math, here is a link: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
You probably want to store the input in a double, so rather than using number.nextLine(), you may want to use number.nextDouble(), and store it in a double, as below.
double value = number.nextDouble();
You were storing the value as a String, so the computer was reading the input as a quotation, like "cat," rather than the numbers. It doesn't work because what you were trying to do was akin to saying
"cat" * "dog."
Good luck in the class!
Hi I have a excel file reading application which reads every cell in the file.
whenever a cell contains a numeric value the app is treating it a numeric cell.
For example the cell contains (40002547) the application will treat this as numeric cell. I cab get the value by using this code:
SONum = String.valueOf(cellSONum.getNumericCellValue());
Well that works fine. My Problem is it appends decimal at the end of the string. it will be (40002547.0). I need it to be as is. Thanks in advance
It's because cellSONum.getNumericCellValue() is returning a floating point type. If you force it to an integer before calling valueOf(), you should get the string representation in an integral form, if indeed that's what you want for all possibilities:
SONum = String.valueOf((int)cellSONum.getNumericCellValue());
You can see this in the following code:
class Test {
public static void main(String[]args) {
double d = 1234;
System.out.println(String.valueOf(d));
System.out.println(String.valueOf((int)d));
}
}
which outputs:
1234.0
1234
However, if you want to just get rid of .0 at the end of any string but allow non-integral values to survive, you can just remove the trailing text yourself:
class Test {
public static void main(String[]args) {
double d1 = 1234;
double d2 = 1234.567;
System.out.println(String.valueOf(d1).replaceFirst("\\.0+$", ""));
System.out.println(String.valueOf(d2).replaceFirst("\\.0+$", ""));
}
}
That snippet outputs:
1234
1234.567
Try with split().
SONum = String.valueOf(cellSONum.getNumericCellValue());
SONum = SONum.split("\\.")[0];
When you split 40002547.0 with . ,the split function returns two parts and the first one you need.
If you want to be sure you are not cutting of any valid decimals, you can use regexp also:
String pattern = "\.0+"; // dot followed by any number of zeros
System.out.println(String.valueOf(cellSONum.getNumericCellValue()).replaceAll(pattern, ""));
More on java regexp for example: http://www.vogella.com/articles/JavaRegularExpressions/article.html
As PaxDiablo also mentions, cellSONum.getNumericCellValue() returns a floating point.
You can cast this to Long or int to get rid of all behind the '.'
String SONum = String.valueOf(cellSONum.getNumericCellValue().longValue());
used as example:
String SONum = String.valueOf((new Double(0.5)).longValue());
SONum = ""+cellSONum.getNumericCellValue().split(".")[0];
try
double value = 23.0;
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(value))
Consider using BigDecimal.
You could simply say
BigDecimal scaledDecimal = new BigDecimal(value).setScale(0, RoundingMode.HALF_EVEN);
This will help in case your input is String and you need result also in String
1). Convert the string to Double using Double.parseDouble,
2). Type cast to int, then convert to string using String.valueOf()
private String formatText(String text) {
try {
return String.valueOf((int) Double.parseDouble(text));
} catch (NumberFormatException e) {
return text;
}
}
You can do Explicit type casting to remove the decimals,
double desvalue = 3.586;
int value = (int)desvalue;
How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?
I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"
double d = 9.01236789E9;
System.out.println(BigDecimal.valueOf(d).toPlainString());
While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.
If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
double value = 9.01236789E9;
String text = String.format("%.0f", value);
System.out.println(text); // 9012367890
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
format.setGroupingUsed(false);
System.out.println(format.format(value)); // 9012367890
}
}
Try String.format("%20.0f", 9.01236789E9)
Note though it's never an exact value, so "preserving every digit" doesn't really make sense.
You can use it.
String doubleString = Double.toString(inValue)
inValue -----> Described by you.to what position you want to Change double to a string.
In this case, you can also do
double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890