Fixed point decimal .java For this program, you\'ll implement a class called Fix
ID: 3670406 • Letter: F
Question
Fixed point decimal .java
For this program, you'll implement a class called FixedPoint that allows you to represent real
numbers with a fixed number of decimal places (from 1 to 5 decimal places) and to perform
exact arithmetic (addition and subtraction) and to display these values.
For example, if I add the double values 6.3 and 7.6, the value displayed would be
13.899999999, not the actual value of 13.9. This is due to the approximation of the of the
intial values when put into Java's floating point representation. Your FixedPoint should allow
you to add 6.3 and 7.6 to produce exactly 13.9.
Your class should have the following constructors to allow you to intialize a new FixedPoint
object:
• public FixedPoint(int d, int w, int f)
constructs a fixed point decimal number with d digits to the right of the decimal
point, with w as the value to the left of the decimal point (the whole part) and f as
the value to the right of the decimal point (the fractional part). For example,
new FixedPoint(2, 3453, 345) will produce an object to hold the value of 3453.34.
• public FixedPoint(int d, String f)
constructs a fixed point decimal number with d digits to the right of the decimal
point, where the whole and fractional parts are initialized from a string representing
a real number. For example, new FixedPoint(2, "3452.345") will produce the same
object as above.
You class will provide the following methods:
• public FixedPoint add(FixedPoint f)
add the fixed point value in the object f to this fixed point object:
FixedPoint f1 = new FixedPoint(2, "71.56");
FixedPoint f2 = new FixedPoint(2, 44, 30);
System.out.println(f1.add(f2)); // will display 115.86
Adding two FixedPoint objects with different numbers of decimal places can return
a null value as a not defined condition.
• public String toString( )
convert the fixed point decimal value f to its string representation. f2.toString()
should produce the Java String object "44.30".
FixedPoint should be defined as a non-public class in your FixedPointdDecimal.java program
file. It should not be a nested class. FixedPointDecimal will be the public class in the program
file and will have the main method to start execution.
Your main method should demonstrate the creation of several fixed point values using
Explanation / Answer
public class AdditionClass {
static double roundToDecimalPlaces(double value, int decimalPlaces)
{
double shift = Math.pow(10,decimalPlaces);
return Math.round(value*shift)/shift;
}
public static void main(String[] args) {
System.out.println(roundToDecimalPlaces(12.78945,3));
//here the second argument is variable.....you can put anything over there
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.