Getting answer of method to two decimal places - java

I am using the code below to get the answer of a method i created into two decomal places. But when I do this and complile i get an error saying identifier expected. 2 error come up one pointing at the 2 and the other just before. what is my problem?
import java.text.NumberFormat;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);

What you've shown is correct, assuming that the lines aren't all together (import statements must be outside of any class). So for instance, this is valid:
import java.text.NumberFormat;
class MyClass {
void someMethod() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
// ...
}
}
...but those lines together as shown in your question are not.
If that's not it, you said that the error seems to focus on the 2. Sometimes when we see questions like this here on SO, it's because some zero-width or space-like special character has accidentally ended up in the source. So it may be that if you delete that line and retype it, you'll wipe out the offending character. (It's actually surprising how often that comes up.)

You can write a general purpose function as follows:
public static double round(double inputNumber, int fractionDigits, int roundingMode) {
BigDecimal bigDecimal = new BigDecimal(inputNumber);
BigDecimal rounded = bigDecimal.setScale(fractionDigits, roundingMode);
return rounded.doubleValue();
}
Please find below the sample test results:
import java.math.BigDecimal;
public class RoundHelper {
public static void main(String[] args) {
System.out.println(RoundHelper.round(123.98980, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.98000, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.98000, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.55087, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(RoundHelper.round(123.14000, 2, BigDecimal.ROUND_HALF_UP));
}
public static double round(double inputNumber, int fractionDigits, int roundingMode) {
BigDecimal bigDecimal = new BigDecimal(inputNumber);
BigDecimal rounded = bigDecimal.setScale(fractionDigits, roundingMode);
return rounded.doubleValue();
}
}
Output:
123.99
123.98
123.98
123.55
123.14

Related

convert double to percent in java 1.5 = 50%

i have this code, variables first, second and third only can obtain in double i need format in percent to write later on other place
import java.text.DecimalFormat;
public class Main {
public static void main(String[] argv) throws Exception {
double first = 0.5;
double second = 1.5;
double third = 2.5;
DecimalFormat df = new DecimalFormat("#%");
System.out.println(df.format(first));
System.out.println(df.format(second));
System.out.println(df.format(third));
}
}
output:
50%
150%
250%
i need obtain this result
-50%
50%
150%
i hope any can help me with this thanks
I looks like you need values relative to 100%, so you just need to subtract 1 (i.e. 100%) from your values:
System.out.println(df.format(first - 1));
System.out.println(df.format(second - 1));
System.out.println(df.format(third - 1));

Why isn't this Ackermann function working?

I would expect this to return with 7, given the input of (2,2). Instead of getting a proper output, the program returns a java.lang.StackOverflowError at line 16.
package main;
import java.math.BigInteger;
public class Ackermann {
public static void main(String[] args) {
System.out.println(ack(BigInteger.valueOf(2),BigInteger.valueOf(2)));
}
public static BigInteger ack(BigInteger a, BigInteger b) {
BigInteger ans;
if (a.equals(0)) ans = b.add(BigInteger.ONE);
else if (b.equals(0)) ans = ack(a.subtract(BigInteger.ONE),BigInteger.valueOf(1));
else ans = ack(a.subtract(BigInteger.ONE), ack(a,b.subtract(BigInteger.ONE))); //line 16
return (ans);
}
}
I've increased the maximum stack size all the way up to 2GB, but it's still throwing the error at the small input of (2,2). Before I started using the BigIntegers instead of Longs, everything worked out fine with the input (2,2), but now it's a mess.
Instead of equals(0) you have to use equals(BigInteger.ZERO).
Otherwise you compare a BigInteger to an Integer (auto boxing) which will always be false.

How to add a very small number and a very large number

I am pretty new to Java. I am learning numerical computation at the moment. How does one add and multiply a very small number and a very large number, say something of order $10^{-20}$ and something of order $10^{20}$ to arbitrary precision.
Take a look at the BigDecimal class. From the Javadoc:
Immutable, arbitrary-precision signed decimal numbers.
and:
The BigDecimal class gives its user complete control over rounding behavior.
For your example:
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal big = new BigDecimal("10e20");
BigDecimal small = new BigDecimal("10e-20");
BigDecimal ans = big.add(small);
System.err.println("Answer: " + ans);
}
}
Running gives the following:
$ java Main
Answer: 1000000000000000000000.00000000000000000010
Try the following (didn't count the zeros). You may find other methods to construct 10^20/10^-20 more suitable.
System.out.println( new BigDecimal("0.0000000000000000000000000000001").add( new BigDecimal
("100000000000000000000000000000000")));

Java : Rounding a decimal value to HALF_EVEN

I have been trying to write a java code to Round a value to the below requirement.
If x=63.88 => roundedValue= 64.00;
If x=63.50 => roundedValue= 64.00
If x=63.32 => roundedValue= 63.32
I tried with the different roundingModes like CEILING, DOWN, FLOOR, HALFDOWN.
I also tried Math.round();
But I'm unable to get the expected output.
My input is a string and output is a string.
Please find the code snippet I tried below
BigDecimal value1 = new BigDecimal(input);
value1=value1.setScale(2, RoundingMode.HALF_EVEN);
//float rounded=Math.round(amount);
String finalValue=String.valueOf(value1);
I'm unable to get the desired output. Please let me know how to achieve this?
ps: should i consider using float or BigDecimal??
if(x%1 >= .5)
{ x = Math.round(x) }
else //do nothing
This seems like it would give you the desired output you are looking for. So if you really wanted to you could override or create your own method to call for the rounding
What you want to do with this, is providing your own MathContext to specify the behavior of the rounding you want to perform.
The closest you will get to your current requirements is either: using RoundingMode.HALF_UP or RoundingMode.UNNECESSARY
For that you will have to use BigDecimal anyways, since Double and Float do not expose rounding.
public static void main(String args[]) {
Double d = 63.18;
DecimalFormat df = new DecimalFormat("00.00");
if(d % 1 >= 0.5)
System.out.println(df.format(Math.round(d)));
else
System.out.println(d);
}
As in your post, using BigDecimal is the way to go, if you want to use decimal rounding.
If you want to round up for numbers >= X.5 and avoid rounding for numbers < X.5 then you can use this code:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Round {
public static void main(String[] args) {
System.out.println(round("63.88"));
System.out.println(round("63.50"));
System.out.println(round("63.32"));
}
private static BigDecimal round(String input) {
BigDecimal value = new BigDecimal(input);
BigDecimal rounded = value.setScale(0, RoundingMode.HALF_UP);
if (rounded.compareTo(value) > 0)
return rounded.setScale(2);
return value;
}
}
The output is:
64.00
64.00
63.32

Wrong output calculating the power

I've the below code.
import java.util.ArrayList;
import java.math.*;
import java.util.Arrays;
import java.util.Collections;
public class Dummy {
public static void main(String args[]) throws Exception {
int n=12;
double val=(3+Math.sqrt(5));
double ne=Math.pow(val, n);
String new2=String.valueOf(ne);
System.out.println(ne);
String[] new1=new2.split("\\.");
if(new1[0].length()>3){
new1[0]=new1[0].substring(Math.max(new1[0].length() - 4, 0));
if(new1[0].length()<3){
new1[0]=("0").concat(new1[0]);
}
else{
new1[0]=new1[0];
}
}
else if(new1[0].length()<2){
new1[0]=("00").concat(new1[0]);
}
else if(new1[0].length()<1){
new1[0]=("000").concat(new1[0]);
}
else if(new1[0].length()<3){
new1[0]=("0").concat(new1[0]);
}
System.out.println(new1[0]);
}
}
here i'm trying to calculate sum of 3 with root 5 and whole to power of 12
(3+sqrt(5))^12
when i do it the result i get is 4.246814719604947E8 but in real the answer is to be 424681471.960494. please let me know where am i going wrong.
It's in the scientific notation.
If you don't want it in this notation, you can try
public static void main(String[] args) {
Double d = Math.pow(3+Math.sqrt(5),12);
System.out.println(d); //4.246814719604947E8
System.out.println(new BigDecimal(d).toPlainString()); //424681471.960494697093963623046875
}
Use this
System.out.println(String.format("%f", ne));
Did you notice the E8 in your answer? Then the answer is correct :)
The answer you are getting is correct.
4.246814719604947E8 means 4.246814719604947 times 10^8. If you move the decimal point 8 places to the right you see the answer you expect.

Categories