Calculating decimal representation of an integer in Java - java

This might seem really naive but I am not sure what is the decimal representation of an integer?
Can you provide some code in Java to convert an integer to its decimal representation?
Thanks!

My answer would have been Integer.toString(value).
Done! I have now "calculated" the decimal representation of an integer (int value).
As the javadoc says:
The argument is converted to signed decimal representation and returned as a string.
Of course, they probably wanted you to write the code that implements that method, rather than using the library method.

You can use things like this :
Integer i = 10;
Double iDecimal = new Double(i);
System.out.println(iDecimal); //would print 10.0 i.e. decimal

Related

BigDecimal Java. How to append zeros in front

My question is basically the following:
When I use a value with BigDecimal, how do I append zeros in front of a random number?
Say I want to have a number <10 following an entirely random pattern. Now i want to add zeros in front of the number, so the actual amount adds up to 10 numbers.
Here's an example:
BigDecimal num = new BigDecimal(2353);
Now I want to have that ouput:
0000002353
Is there a function that appends numbers to a BigDecimal type?
I couldn't find any.
I tried using a while loop that checks whether the number is less than ten. But I don't understand the Big Decimal well enough to actually compare integral values to the BigDecimal types.
Thanks for any help in advance!
If you use a BigInteger instead (or any integer type, such as int or long) you can format the value with
String.format("%010d", BigInteger.valueOf(2353))
The leading 0 in the format strings means pad with 0, the following 10 is the desired length...
BigDecimal is meant to be used for storing large floating point numbers. Since in a floating-point number there isn't any difference between 0000002353 and 2353, there is no reasonable way to append leading 0's to a BigDecimal just as there is no reasonable way to append leading 0's to a normal float. According to the behavior you're looking for, I would suggest using a String to store your number, and then convert to and from BigDecimal when you want to perform any operations.
To compare an integral type to a BigDecimal, first convert the variable to a BigDecimal and then call BigDecimal's compareTo method. More info is in this question.
Since you're interested in formatting the number, you might want to look at DecimalFormat class, which allows to format floating point and integer numbers according to the specified pattern.
BigDecimal num = new BigDecimal(2353);
DecimalFormat f1 = new DecimalFormat("0000000000");
DecimalFormat f2 = new DecimalFormat("0,000,000,000");
System.out.println(f1.format(num));
System.out.println(f2.format(num));
Output:
0000002353
0,000,002,353
If the maximum number of digits is 10 and only whole numbers are allowed you don't need anything more than to use long with standard formatting:
long myNumber = 123456;
System.out.printf("%010d%n", myNumber);

How to convert String to BigInteger when var contains ".0"

I've got a String variable that may contain a number such "2015.0".
When I try to convert it to int with
int i = Integer.parseInt(myVar)
or BigInteger with
BigInteger bi = new BigInteger(myVar)
I get the error
java.lang.NumberFormatException: For input string: "2015.0"
How can I achieve a correct cast?
Thanks!
You can parse it as a BigDecimal and then convert to BigInteger
BigInteger bi = new BigDecimal("2015.0").toBigInteger()
Just note that you may lose precision information when doing this:
...any fractional part of this BigDecimal will be discarded. Note that this conversion can lose information about the precision of the BigDecimal value.
To have an exception thrown if the conversion is inexact (in other words if a nonzero fractional part is discarded), use the toBigIntegerExact() method.
As suggested in the quoted javadocs, use toBigIntegerExact() to prevent accidental losses of precision such as the one that would result from converting "2.5" to BigInteger (thanks to Ole V.V.'s comment for this remark).
You can also just parse it to a double and then drop the decimal part by casting it to int
int i = (int) Double.parseDouble(myVar);
You can't convert a float to a BigInteger, and your string has a decimal point, so it's automatically considered to be a float. You have a couple of options, but the easiest might be to strip off the decimal portion from the string to get "2015", and then use that to construct your BigInteger.
That's assuming that the decimal portion of the number doesn't matter, of course. If it does, consider using BigDecimal, instead.

BigDecimal getting rounded..but i do not want any rounding

In my code i want to insert into db without any rounding or exponentiation ..but it is converted in my java code when i use a sop as 2.631578947368421E-7
Below is the code i use:
BigDecimal a =new BigDecimal(0.0000002631578947368421052631578947368421052632,MathContext.DECIMAL64);
System.out.println(a);
I just want it to be maintained as it is because i want to do some calculations .
Please do provide me an apt solution.
Construct the big decimal using a String, otherwise the constant you enter gets rounded before it is passed as argument to the constructor of BigDecimal.
So write something like this:
BigDecimal a =new BigDecimal("0.0000002631578947368421052631578947368421052632");
System.out.println(a.toPlainString());
And all should work.
EDIT: you should also get rid of the second argument of the constructor as
static MathContext.DECIMAL64 means: A MathContext object with a precision setting matching the IEEE 754R Decimal64 format, 16 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
EDIT2: also use a.toPlainString() when printing to not use scientific notation.
You can use MathContext.UNLIMITED.
BigDecimal a =new BigDecimal(0.0000002631578947368421052631578947368421052632,MathContext.UNLIMITED);
System.out.println(a);
System.out.println(a.toPlainString());
When you print value you can use BigDecimal.toPlainString() to return "a string representation of this BigDecimal without an exponent field".
BIgDecimal getting rounded.
No it isn't. BigDecimal has nothing to do with it. The constant value 0.0000002631578947368421052631578947368421052632 is getting rounded. It cannot be represented exactly in floating-point.If you want an accurate BigDecimal with this value, use new BigDecimal(String).

Java Math.pow() Rounding Error

I'm having trouble with (what I suspect is) a rounding error.
I have a string, 0.686357E-01, which I'm trying to convert to a double. I've been able to split it up using the Pattern.split() function, and I'm capturing the base and the exponent values just fine. However, once I try to multiply them appropriately, I get this as a result: 0.06863570000000001.
Here's my relevant code:
pattern = Pattern.compile("E\\+?");
String[] number = pattern.split(string);
double base = Double.parseDouble(number[0]);
int exponent = Integer.parseInt(number[1]);
number= base*Math.pow(10, exponent);
So, how do I avoid the rounding error? (There are ways that I can work around it, but if it's possible to do, then I'd like to know how to fix the issue)
Thanks.
You don't need to split it, Double.parseDouble can handle those kinds of numbers just fine.
double number = Double.parseDouble("0.686357E-01");
See? It works!
0.0686357 is not exactly representable as a double-precision value.
Two solutions:
Use e.g. BigDecimal.
Limit the displayed precision to a certain number of significant figures when converting back to human-readable.
Floating point numbers do not have perfect precision. If that is an issue, use BigDecimal:
String string = "0.686357E-01";
BigDecimal number = new BigDecimal(string);
System.out.println(number);
Double will print always like that, but the value will remain correct. You'll need to format the output to get the correct value. See DecimalFormat class.

71674705 value converted to 7.1674705E

I have big problem with reading big numbers from excel in java. When i read 71674705 i get 7.1674705E which is not ok.
Example:
double num =
cell.getNumericCellValue();
how can i prevent conversion between numbers that number will stay like 71674705.
The number itself is not changing, only the representation when you convert it to a String. A double variable like you are using does not have an explicit format defined.
You can use java.text.NumberFormat (javadoc) to format the number any way you would like to see it.
num is just a double, i.e. a binary floating-point number. That formatting (exponential notation) is only an issue for printing. So if you're just debugging, you shouldn't have to worry. For production output, you can use a NumberFormat such as DecimalFormat.
If you are sure you are dealing with an integer and you want it as an integer value you can always try to do:
Integer.valueOf(num)
Edit: not valid for big numbers of course :-)

Categories

Resources