/ Published in: Java
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import java.util.*; /* Data Objects */ private double value; /* Constructors */ value = 0; } value = inputvalue; } value = n.value; } /* Accessors */ public double value(){ double n = value; return n; } /* Mutators */ public void set_value(double inputvalue){ value = inputvalue; } value = inputvalue.value; } public MyString myString(int n){ Formatter fmt = new Formatter(); MyString output = new MyString("" + fmt.format("%."+n+"f", value)); return output; // MY OWN ALGORITHM FOR SETTING THE PRECISION OF MY NUMBER. // // say we start with value=17.55745 and we want a decimal precision of n=2. // // make an int version of double: // int b = (int)value; // b == 17 // // subtract int version from double to leave the decimal places: // double c = value - b; // c = 17.55745 - 17 == .55745 // // multiply by (10^n) to find the decimals. // double d = c * Math.pow(10,n); // d == 55.745 // // make another int of the decimals: // int e = (int)d; // e == 55 // // subtract the int from the decimal double: // double f = d - e; // f == .745 // // if f is < 0.5 then leave e alone. // e == 55 // // if f is >= 0.5 // if ( f >= 0.5 ) { // // then add 1 to e: // e++; // e == 56 // } // // now output the parts as a string: // MyString output = new MyString("" + b + "." + e); // return output; // // say we start with value=17.00745 and we want a decimal precision of n=2. // // make an int version of double: // int b = (int)value; // b == 17 // // subtract int version from double to leave the decimal places: // double c = value - b; // c = 17.00745 - 17 == .00745 // // multiply by (10^n) to find the decimals. // double d = c * Math.pow(10,n); // d == 00.745 // // make another int of the decimals: // int e = (int)d; // e == 0 // if (e < Math.pow(10,n-1)) { // // } // // subtract the int from the decimal double: // double f = d - e; // f == .745 // // if f is < 0.5 then leave e alone. // e == 55 // // if f is >= 0.5 // if ( f >= 0.5 ) { // // then add 1 to e: // e++; // e == 56 // } // // now output the parts as a string: // MyString output = new MyString("" + b + "." + e); // return output; } public MyString myString(){ return new MyString("" + value); } return "" + value; } } } } } } } } } }