is there a more effecient way to calculate....
:chopping off the integer part of a Double/Float:
double d = 'some double';
d -= (int)d; //is this the best way?
example
-3.19283 --> -0.19283
0.9999-->0.9999
11.00192 -->0.00192
:dividing out and rounding:
double ak = 'some double';
double r = 'some double';
r -= (int)(r / ak) * ak;
[374 byte] By [
ctmoore] at [2007-9-27 18:53:08]

minor correction:
should actually be StrictMath.IEEEremainder
also... be aware that the actual number may
be slightly different. for example,
public class ChopOffAfterDecimal
{
public static void main( String [ ] args )
{
double d = 4.19283 ;
System.out.println( d );
System.out.println( StrictMath.IEEEremainder(d, 1) );
System.out.println( d%1 );
System.out.println( Math.floor( d ) );
}
}
yields:
4.19283
0.19282999999999983
0.19282999999999983
4.0
So if you want as an answer: .19283, none of the answers so far will do. But I'm not sure what the best way would be short of turning it into a string, or some other crazy procedure, to allow exact truncation without rounding side-effects.
I think this is the best way.no side efffects.go throguh it
import java.text.*;
public class Test extends DecimalFormat {
private int scale = 1;
/**
* Constructor Test
*
*
*/
public Test () {}
/**
* Method setScale
*
*
* @param scale
*
*/
public void setScale (int scale) {
this.scale = scale;
}
/**
* Method getScale
*
*
* @return
*
*/
public int getScale () {
return scale;
}
// Use this methos before passing to format method
/**
* Method formatToDec
*
*
* @param dl_Value
*
* @return
*
*/
public double formatToDec (double dl_Value) {
double rounded = Math.round (dl_Value * getScaleValueOne ()) /
getScaleValueOne ();
rounded = Math.round (rounded * getScaleValue ()) /
getScaleValue ();
System.out.println("the rounded value ***111*** is"+rounded);
return rounded;
}
/**
* Method formatToDec
*
*
* @param dl_Value
*
* @return
*
*/
public float formatToDec (float dl_Value) {
double rounded = Math.round (dl_Value * getScaleValueOne ()) /
getScaleValueOne ();
rounded = Math.round (rounded * getScaleValue ()) /
getScaleValue ();
System.out.println("the rounded value ****345***is"+rounded);
return (float) rounded;
}
/**
* Method formatToDecString
*
*
* @param dl_Value
*
* @return
*
*/
public String formatToDecString (float dl_Value) {
double rounded = formatToDec (dl_Value);
return format (rounded);
}
/**
* Method getScaleValue
*
*
* @return
*
*/
private double getScaleValue () {
int scale = getScale ();
if (scale < 2) {
scale = getMinimumFractionDigits ();
}
return Math.pow (10, scale);
}
private double getScaleValueOne () {
int scale = getScale ()+2;
if (scale < 2) {
scale = getMinimumFractionDigits ();
}
return Math.pow (10, scale);
}
public static void main(String[] args){
Test t=new Test();
t.setScale(2);
float x=0.9f;
float y=8.15f;
t.setScale(2);
System.out.println("the value 4 is"+t.formatToDec (62.75f * 1.18f));
}
}