Any way to avoid results containing "9.223372036854776E18" - java

I'm making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);

Other answers are correct, you could use a java.text.NumberFormat (JavaDoc) to format your output. Using printfis also an option for formatting, similar to NumberFormat. But I see something else here. It looks like you mixed up your data types: In
nq = (long) Math.pow(2l, 1000l);
you are already truncating the double return value from Math to a long. Then you should use long as data type instead of double for the conversion. So use Long.toString(long), this will not add any exponent output.
Use Long.toString(nq) instead of Double.toString(nq); in your code.

As you say: "NumberFormat". The class.

BigInteger is easy to use and you don't risk precision problems with it. (In this particular instance I don't think there is a precision problem, because Math.pow(2, 1001) % 100000 returns the correct last 5 digits, but for bigger numbers eventually you will lose information.) Here's how you can use BigInteger:
groovy:000> b = new BigInteger(2L)
===> 2
groovy:000> b = b.pow(1001)
===> 214301721437253464189685009812000362112280962341106721488750077674070210224
98722449863967576313917162551893458351062936503742905713846280871969155149397149
60786913554964846197084214921012474228375590836430609294996716388253479753511833
1087892154125829142392955373084335320859663305248773674411336138752
groovy:000> ((b + "").toList().collect {new Integer(it)}).inject(0) {sum, n -> sum + n}
===> 1319
Here's the same thing in Java:
public class Example
{
public static void main(String[] args)
{
int sum = 0;
for (char ch : new java.math.BigInteger("2").pow(1001).toString().toCharArray()) {
sum += Character.digit(ch, 10);
}
System.out.println(sum);
}
}

Link to the javadoc for NumberFormat: Javadoc

just replace last line:
System.out.println(result);
with
System.out.printf("%d", result);

Related

Java code snippet to trim the decimal places in a number based on a condition [duplicate]

I am invoking a method called "calculateStampDuty", which will return the
amount of stamp duty to be paid on a property. The percentage calculation works
fine, and returns the correct value of "15000.0". However, I want to display the value to
the front end user as just "15000", so just want to remove the decimal and any preceding values
thereafter. How can this be done? My code is below:
float HouseValue = 150000;
double percentageValue;
percentageValue = calculateStampDuty(10, HouseValue);
private double calculateStampDuty(int PercentageIn, double HouseValueIn){
double test = PercentageIn * HouseValueIn / 100;
return test;
}
I have tried the following:
Creating a new string which will convert the double value to a string, as per below:
String newValue = percentageValue.toString();
I have tried using the 'valueOf' method on the String object, as per below:
String total2 = String.valueOf(percentageValue);
However, I just cannot get a value with no decimal places. Does anyone know
in this example how you would get "15000" instead of "15000.0"?
Thanks
Nice and simple. Add this snippet in whatever you're outputting to:
String.format("%.0f", percentageValue)
You can convert the double value into a int value.
int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
I did this to remove the decimal places from the double value
new DecimalFormat("#").format(100.0);
The output of the above is
100
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
You can convert double,float variables to integer in a single line of code using explicit type casting.
float x = 3.05
int y = (int) x;
System.out.println(y);
The output will be 3
I would try this:
String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.
int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Try this you will get a string from the format method.
DecimalFormat df = new DecimalFormat("##0");
df.format((Math.round(doubleValue * 100.0) / 100.0));
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Use
Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)
the simple way to remove
new java.text.DecimalFormat("#").format(value)
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.
String newValue = ((int) percentageValue).toString();
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose
The problem is two fold-
To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
Double i = Double.parseDouble("String with double value");
Log.i(tag, "display double " + i);
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); // set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]", "");
Double i = Double.parseDouble(result);
int max = Integer.parseInt(result);
} catch (Exception e) {
System.out.println("ex=" + e);
}
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
This should do the trick.
System.out.println(percentageValue.split("\\.")[0]);
Try:
String newValue = String.format("%d", (int)d);

Summing BigInteger Digits

I am trying to find the sum of the digits of the number 2^1000 and I am using Java BigInteger class for this. However, I could not make it real. Eventually, I get a 0 (zero) with the following code. What might be the problem?
Thanks...
After Kon's help I fixed the problem, but this time I get a wrong result. Can anyone see the problem with the algorithm?
public static void main(String []args) throws Exception
{
BigInteger big = BigInteger.valueOf(2).pow(1000);
BigInteger big2 = BigInteger.valueOf(0);
//System.out.println(big);
for(long i = 1; i<283; i++)
{
big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
}
System.out.println(big2);
}
Trying to calculate each digit of BigInteger using mod is not very efficient, because of many method calls you are doing in the process. Instead you can simplify by doing the conversion to String and getting each digit straight away.
BigInteger big = BigInteger.valueOf(2).pow(1000);
String digits = big.toString();
int sum = 0;
for(int i = 0; i < digits.length(); i++) {
int digit = (int) (digits.charAt(i) - '0');
sum = sum + digit;
}
System.out.println(sum);
The BigInteger class is immutable, therefore you have to assign the result of the operation to the variable itself.
big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
should become
big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
For more on immutable objects in Java, please take a look at this documentation.
Also, although your question is not specifically about this, using hard coded literal values in your loops is very bad practice. You want to loop over each digit in the BigInteger 2^1000. Well, you could get the number of digits using something like big.toString().length().

Only return a decimal if it's not a whole number. JAVA

I've been trying to write a function isWhole that is given a double and looks to see if it's a whole number if it is return the value without the decimal(as an int?) else return it with 3 decimal places(I can do this part with number format.
My question is how can I check if a double is a whole number and even a recursive decimal?
[UPDATE] returns value - with 3 decimal places
public boolean isWhole(double value) {
return Math.floor(value) == value;
}
You can't have a function that returns either int or double
To convert double to int; simply typecast :- int valueInt = (int) valueDouble;
My first advice would be: keep it simple. Java has functions that make this sort of thing easy:
import java.Math;
public class MyFunctionsLibrary {
public static boolean isWhole(double x) {
if(x - Math.floor(x) == 0)
return true;
else
return false;
}
public static void testIt() {
double a = 123.456;
Integer whole = null;
Double nonWhole = null;
if(isWhole(a))
whole = new Integer(Math.floor(a));
else
nonWhole = new Double(a);
}
}
if(Math.abs(in-Math.floor(in)) < 0.001){
/* is whole number */
} else {
/* is not whole number */
}
Whole number isn't really defined for doubles, so a whole number can be seen as a number that has would not result in n.000. 0.001 is chosen specifically because it is the intended output precision.
This was my original answer:
How about
Math.floor(x)==x
The floor leaves the x unchanged, bit-by-bit if it is a mathematical integer (say the docs), so the equality should hold exactly when there is nothing to round.
After some thought, I think using exact comparison may lead to unwanted results. The question is, what the requirements of the OP really are. Is it
If it is a mathematical integer, show the number with no digits
after the decimal point, if it is not, show 3 digits after the
decimal point. Or is it
If formatting with three digits results in 000 after the decimal point, show only an integer.
The solution shown above and in other answers only works, if (1) is the requirement, because the number 2.000001 would turn out as 2.000, because it is not a mathematical integer.
If the Locale is fixed to a default, formatting 1.0 for the endsWith()-pattern can of course be optimized into a fixed string like ".000" or ",000".
If (2) is actually requested, my hunch is that there is no way around first formatting the number to a string and only then stripping the zeros, like so:
String format(Locale l, double d) {
String zeros = String.format(l, "%.3f", 1.0d);
String s = String.format(l, "%.3f", d);
if (s.endsWith(zeros.substring(1))) {
return s.substring(0, s.length()-4);
}
return s;
}
To see if a double is a whole number use
double d;
int whole = (int) d;
if(whole == d){
return whole;
}
else{
(your formatting here)
return formattedDouble;
}
You could check if it is recursive by creating:
String s = d + "";
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i-1)){
continue;
}
else{
return false;
}
}

How can I use parseInt for a double?

My program receives some input (a String). It is rather possible that the input is in the form of a double, like "1.5". But I would like to convert it to an integer, so I can end up with just a 1.
First, I tried this:
Integer.parseInt(someString);
But it doesn't work - I'm assuming it is because of the dot . that it can't parse it.
So I thought that maybe the Integer class can create an integer from a double. So I decided to create a double and then make it an int, like this:
Integer.parseInt(Double.parseDouble(someString));
But apparently there is
no suitable method found for parseInt(double)
So, what do you suggest? Are there one-liners for this? I thought about making a method that removes the dot and all characters after it... but that doesn't sound very cool.
It is safe to parse any numbers as double, then convert it to another type after. Like this:
// someString = "1.5";
double val = Double.parseDouble(someString); // -> val = 1.5;
int intVal = (int) Math.floor(val); // -> intVal = 1;
Note that with Java 7 (not tested with earlier JVM, but I think it should work too), this will also yield the same result as above :
int intVal = (int) Double.parseDouble(someString);
as converting from a floating value to an int will drop any decimal without rounding.
use casting.
double val = Double.parseDouble(someString);
int intVal = (int) Math.floor(val);
You've got the Double, I assume, with Double.parseDouble. So just use:
int i = (int) Double.parseDouble(someString);
Try,
int no= new Double(string).intValue();
Try this:
1) Parse the string as double
2) cast from double to int
public static void main(String[] args) {
String str = "123.32";
int i = (int) Math.floor(Double.parseDouble(str));
System.out.println(i);
}

NumberFormatException, BigInteger in java

Getting following run-time error
C:\jdk1.6.0_07\bin>java euler/BigConCheck
Exception in thread "main" java.lang.NumberFormatException: For input string: "z
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.math.BigInteger.<init>(BigInteger.java:314)
at java.math.BigInteger.<init>(BigInteger.java:447)
at euler.BigConCheck.conCheck(BigConCheck.java:25)
at euler.BigConCheck.main(BigConCheck.java:71)
My Code
package euler;
import java.math.BigInteger;
class BigConCheck
{
public int[] conCheck(BigInteger big)
{
int i=0,q=0,w=0,e=0,r=0,t=0,mul=1;
int a[]= new int[1000];
int b[]= new int[7];
BigInteger rem[]= new BigInteger[4];
BigInteger num[]= new BigInteger[4];
for(i=0;i<4;i++)
num[i]=big; // intialised num[1 to 4][0] with big
String s="1",g="0";
for(i=0;i<999;i++)
s = s.concat(g);
BigInteger divi[]= new BigInteger[4];
for(i=0;i<5;i++)
{
divi[i]=new BigInteger(s);
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
divi[i]=divi[i].divide(zz);
}
for(i=0;i<996;i++) // 5 consecative numbers.
{
for(int k=0;k<5;k++)
{
rem[k] = num[k].mod(divi[k]);
b[k]=rem[k].intValue();
mul= mul*b[k];
/*int z = (int)Math.pow((double)10,(double)(k+1));
String zz = "z";
BigInteger zzz = new BigInteger(zz);
num[k]=num[k].divide(zzz); */
}
a[i]=mul;
for(int p=0;p<5;p++)
{
BigInteger qq = new BigInteger("10");
num[p]=num[p].divide(qq);
}
}
return a;
}
public int bigestEleA(int u[])
{
int big=0;
for(int i=0;i<u.length;i++)
if(big<u[i])
big=u[i];
return big;
}
public static void main(String args[])
{
int con5[]= new int[1000];
int punCon;
BigInteger bigest = new BigInteger("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450");
BigConCheck bcc = new BigConCheck();
con5=bcc.conCheck(bigest);
punCon=bcc.bigestEleA(con5);
System.out.println(punCon);
}
}
please point out whats goes wrong # runtime and why
thanks in advance...
This is the line causing you grief:
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
While BigInteger does work with String's, those String's must be parsable into numbers.
EDIT**
Try this:
Integer z = (Integer)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(z.toString());
new BigInteger("z"); is not meaningful. You can only pass numbers in constructor.
This is pretty obvious, so the next time you get an exception go the the exact line in your code shown in the exception stacktrace and you will most likely spot the problem.
BigInteger Javadoc states for BigInteger(String value)
Translates the decimal String
representation of a BigInteger into a
BigInteger. The String representation
consists of an optional minus sign
followed by a sequence of one or more
decimal digits. The character-to-digit
mapping is provided by
Character.digit. The String may not
contain any extraneous characters
(whitespace, for example).
So your code:
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
is totally incorrect, but this is correct:
BigInteger zz = new BigInteger("5566");
EDIT: Based on your comment, this would be simpler by using the String.valueOf() method:
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(String.valueOf(z));
BigInteger zz = new BigInteger("z");
you are passing non-numerical string thats the reason.
EDIT:
It takes string but it expects the string to be a numerical value. "z" does not have any numerical meaning.
Could it be that you want this instead?
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(z);
Note the missing quotes here. (Of course, this will only work for i < 10.)
A common mistake is writing
new BigInteger("",num)
instead of
new BigInteger(""+num)
For those interested in generating longs with characters without hashing, it is possible to transform characters to long via BigInteger simply by using the constructor with a radix: BigInteger(String value, int radix)
There is a catch thought, the int which defines the log base, must scale not with the length of the String, but instead with the number of characters that make out the collection of characters that will be used in the creation of the String.
As far as I'm aware, for an alpha numeric collection, the int is 36 (26 + 10), this may be wrong thought.
There is also a limitation, I believe there are symbols that simply cannot be parsed, like "-" or " " or "_" (I've tried adding to the int base radix and nothing) which means the String must be transformed before parsing and it cannot be returned back to String after it being parsed via BigInteger.
Why is it useful?? I don't know haha, I have use it to autogenerate id's from Strings ,instead of using hashes, I remember somhwere this is kinda better than hashcode since a hash from String does not ensure uniqueness, an also this method as opposed to base Encoding gives extricity a long value, which may be useful for many api's that require a long id.

Categories