Take the decimal part of a double/float number [duplicate] - java

This question already has answers here:
How do I get whole and fractional parts from double in JSP/Java?
(18 answers)
Closed 4 years ago.
I have a simple question, I want to know how can I get the decimal part from a double/float number without the dot.
Example: a=0.75 and b=3231.0131
So I would like to set those decimal values in two new Integer variables: m=75 and b=0131.
I'm going to clarify some things, I want to create a new int variable, that variable will storage the decimal part from the original number.
double a = 0.75
double b = 12.033
int x = decimalofa
int y = decimalofb
System.out.println("the decimal of"+a+"is"+x+"and the decimal of"+b+"is"+y)
//the decimal of 0.75 is 75 and the decimal of 12.033 is 033
The thing is that i'm not sure if 033 could be considered as an integer number, so in other words I just want to take all the numbers next to the point and save them in a new variable.

Just do
float a = 0.75f;
System.out.println(Float.toString(a).split("[.]")[1]);
This only works if there is a decimal and there are numbers after that decimal

Related

Print double with variable precision (not rounded) in Java [duplicate]

This question already has answers here:
Format Float to n decimal places
(11 answers)
Closed 7 years ago.
I am looking to print a double to a variable precision, but without rounding. For example:
Scanner input = new Scanner(System.in);
double num;
System.out.println("Enter a double:");
num = input.nextDouble();
int precision;
System.out.println("Enter precision:");
precision = input.nextInt();
Now I want to print num to the decimal place of precision. Is there a simple way to print this?
EDIT:
I have not seen another question answered as to how to use a variable value. The DecimalFormat option rounds the number, which I do not want. Ideally, I am looking for a way to use a variable in:
"%.nf"
rather than
"%.3f"
Use, as a formatted String, "%.nf", where n is replaced by the number of decimal places.
Example:
System.out.printf("%.1f, %.2f\n", 1.234d, 1.234d);
// 1.2, 1.23
See the Javadoc.
To insert a variable into this, just do "%." + intValue + "f".

How to round Double to significant digit [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I have a application which reads SAS xpt file and stores column value into ByteBuffer and then using getValue() method of it to get Double object. Now I have to print Double upto 12 significant digit after decimal. I found one answer from this from which is working fine but few cases
BigDecimal bd = new BigDecimal(dblColumnData.doubleValue());
System.out.println(String.format("%."+15+"G", bd));
Here 15 is given because there are 3 digits in integer part and there must be 12 significant digit after decimal.
Cases where it is not working is because BigDecimal created from Double. If I print Double then it contains more than 12 digits after decimal and it round correctly with same above approach.
Therefore I think if I can get similar format method for Double the it will solve my problem.
I'd do it somehow like this:
static double roundTo(double d, int digit) {
double exp = Math.pow(10, digit);
d *= exp;
d = Math.round(d);
return d / exp;
}
The following would round the number to 3 places after the comma and print it
public static void main(String[] args) {
System.out.println(roundTo(7.34343434, 3));
}
Will print "7.343"

Round number with Math round: doesn't work [duplicate]

This question already has answers here:
Round number to only first decimal place
(3 answers)
Closed 8 years ago.
I wish I could understand how it is possible that is not rounded the decimal number obtained from the following code.
File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize2 = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
double result = availableBlocks * blockSize;
free = (Preference)this.findPreference("free_mem");
free.setSummary(Double.toString(result)+" GB");
In a code similar to this use this instruction and works
result = Math.round(result * 10) / 10d;
Why not work here and I still see a number with many decimal places?
If I understood your question right you need NumberFormat here:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(result);
This produces a number with 1 decimal places.
So if result is 6.6789 it will produce 6.7.
Related: Round number to only first decimal place
Just a note:
If you do this:
Math.round(result * 10) / 10d;
you basically say:
Multiply result with 10
Round the result
Then divide with ten.
When you got rid of the decimals at step 2. you got another bunch of decimals after the division.

How return only two decimals with float? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
What's the best practice to round a float to 2 decimals? [duplicate]
(7 answers)
Closed 9 years ago.
I've got a float value and i need to have only two decimals after comma. I'm using this code:
public static float getWhatINeed() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
float total =
((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
return total;
}
And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:
String s = String.format("%.2f", 1.2975118);
somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?
There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.
If you really NEED 2 decimals, use BigDecimal
You basically have 4 options:
return a float and deal with the fact that there are n decimal places
format to a String (which means a lot of string parsing if you need to do calculation)
convert to use BigDecimal
convert to use int and assume that the ones digit represents hundredths.
Did you try:
new DecimalFormat("00.00").format(1.2975118);
You can try as follows
DecimalFormat df = new DecimalFormat("0.##");
float a=1.256f;
System.out.println(df.format(a));
}
Out put
1.26
After setting precision and get as a String You can canvert it back to float by
float f = Float.parseFloat(YourString);

Format double to 2 decimal places [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I am trying to Format my double value to exact 2 decimal places and it seems to working fine, here is the code i am trying
final NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
df.format(value)
Till now everything is working, but i need to return double value as it is being used for other calculations and i tried
Double.parseDouble(df.format(value))
with big decimal like
BigDecimal price = new BigDecimal(df.format(number));
but it is not working as expected
like 18.50 is being converted as 18.5
Though this is not an issue with calculations but i need to show amount on the UI where i have to show exactly up to 2 decimal places.
Is there any was i can handle it in java class or i have to take care in JSP with JSTL
This is what BigDecimal is made for!
BigDecimal number = new BigDecimal(123.456);
// set 2 fraction digits
// Note that setScale() does not change the original,
// but returns a new BigDecimal.
number = number.setScale(2, RoundingMode.DOWN);
// get string representation
String text = number.toPlainString();
// get double value
double dbl = number.doubleValue();
And use BigDecimal for other calculations as well if you can.

Categories

Resources