How get float number with no rounded number in java [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 4 years ago.
I have this float 98.01645 and I'm getting 98.02 with this function:
String lastCredit = String.format("%.2f", AppSingleton.getInstance().credit);
That I want is get 98.01 (only two decimals or not rounded number). I'm trying but I can't get the way to do it work.

Doing it manually:
String lastCredit = String.format("%.2f", java.lang.Math.floor(100.0*AppSingleton.getInstance().credit)*0.01);
Multiplying by 100.0 to move the decimal point two to the right, then rounding down, then moving the decimal point two to the left by multiplying with 0.01.

You can try this
String lastCredit = String.format("%.2f",Math.floor((98.01645 * 100)) / 100);
System.out.println(lastCredit);
You basically multiply the value by 100 because you need 2 numbers after the decimal and round down that value. After you have the result you divide it by 100 again.

I would not call this elegant, but you can just use String.format to get 3 decimal places and remove the last using substring:
String lastCredit = String.format("%.3f", AppSingleton.getInstance().credit);
lastCredit = lastCredit.substring(0, lastCredit.length() - 1);

Use below code instead of String lastCredit = String.format("%.2f", AppSingleton.getInstance().credit);
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
String lastCredit = decimalFormat.format(f);

Related

How to make any double datatype into 0.00 (2 digits after decimal point) format taking in another double datatype (Android/Java)? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I'm beginner in android developing. How can I make a double datatype i.e 56.32534 into 56.33? But I want to take it in a double variable. I know a way but it takes in String.
Double value = 56.32534;
DecimalFormat df = new DecimalFormat("0.##");
String newvalue = df.format(value);
Here, newvalueis a string. But I want to take it in a double datatype.
I need to use it's numeric value not just in display purpose only.
You can use Math.round():
double value = 56.32534;
double rounded = Math.round(100 * value) / 100.0;
The multiplication and then division by 100 is necessary because Math.round() rounds to the nearest long value.
If you want to generalize this to a variable number of digits, you can use something like this:
public double round(double value, int digits) {
double scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
This will even work if digits is not positive; it will round to the nearest integer if digits is 0, to the nearest 10 if digits is -1, to the nearest 100 if digits is -2, etc.
We need a little bit more precision on what you want to do. Do you want to display it that way or just use its numerical value that way ?
If it's the display your solution is ok. You could always get back the float number from the string afterwards.
On the other hand if you want to use it as a numerical value what you could do is
double rounded = (double) Math.round(myfloat * 100) /100;
I think it works. Can't test it as I'm on my mobile though

multiply Bigdecimal and int generating error [duplicate]

This question already has answers here:
How to multiply a BigDecimal by an integer in Java
(3 answers)
Closed 8 years ago.
I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below
Bigdecimal x=BigDecimal.valueOf(0.0004)
Now I am trying to multiply as x*100 but I am getting below error.
Error: The operator * is undefined for the argument type(s) BigDecimal, int
Because of this error if I use this without bigdecimal again it is converting to EXponential.
Can any one please suggest me the way to multiply Bigdecimal and int.
googled a lot but couldn't find the correct solution.
Thanks for your time
You can use BigDecimal.multiply to multiply your BigDecimal.
However, the int value of 0.0004 * 100 will be 0, which is probably not what you want.
Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your Number.
Here's an example:
BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));
Output
y is 0.04000 z is 0
y (2 fraction digits) is 0.04
BigDecimal's are objects. They don't have normal operators.
Instead of a normal multiplication operator like x*10, you need to call the method multiply in BigDecimal:
x = x.multiply(new BigDecimal(10));
If you want to store it in a new value:
BigDecimal n = x.multiply(new BigDecimal(10));
And to convert that to a primative:
double d = n.doubleValue();
int i = n.intValue();
However, if you're trying to use decimals, why not just use a double:
double x = 0.0004;
double n = x*100;

Showing and not showing dot and decimals in float values? [duplicate]

This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 9 years ago.
How can I make a float value to only show the dot and the decimals if they exist. For example show 17 instead of 17.0 but if I have a 17.2 show the dot and the decimals.
Thanks!
You might also require to limit the length of fraction part, because there might a result like 12.00001 after a sequence of floating point operations. Code snippet I use to nicely format a double to a string:
private static final DecimalFormat[] formats= new DecimalFormat[]{
null,
new DecimalFormat("#.#"),
new DecimalFormat("#.##"),
new DecimalFormat("#.###"),
new DecimalFormat("#.####")
};
public static String toConciseString(double d, int fractionLength){
long asLong = (long) d;
if(Math.abs(d - asLong) < 0.00001d){
return Long.toString(asLong);
}
return formats[fractionLength].format(d);
}
Test cases showing the output examples:
assertThat(toConciseString(23.323, 2)).isEqualTo("23.32");
assertThat(toConciseString(23.329, 2)).isEqualTo("23.33");
assertThat(toConciseString(23.329, 3)).isEqualTo("23.329");
assertThat(toConciseString(23.3, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.30001, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.00001, 2)).isEqualTo("23");
Try this:
DecimalFormat decimalFormat = new DecimalFormat("#0.##");
float float1 = 1.00f;
float float2 = 1.02f;
System.out.println(decimalFormat.format(float1));
System.out.println(decimalFormat.format(float2));
It will print out:
1
1.02

how to change the double value as four decimal point value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Round a double to 2 significant figures after decimal point
i've got lat and long point like this,
x1: 11.955165229802363
y1: 79.8232913017273
i need to convert 4 decimal point
x1 = 11.9552
y1 = 79.8233
Try
double roundTwoDecimals(double d)
{
DecimalFormat twoDForm = new DecimalFormat("#.####");
return Double.valueOf(twoDForm.format(d));
}
Math.ceil(x1* 10000) / 10000
Replace 10000 with 10^N, where N is number of digits after dot. In case of 4 digits after dot, precision shouldn't be lost.
Try this
String.format("%.4f", 11.955165229802363)
Assuming you want to round/truncate the decimal, and speed is not a large consideration, you want to use BigDecimal(BigInteger unscaledVal, int scale) with scale set to 4.
DecimalFormat dtime = new DecimalFormat("#.####");
^^^^
x1= Double.valueOf(dtime.format(x1));
float round = Round(num,4);
System.out.println("Rounded data: " + round);
}
public float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
If you only want to display the value like that, use a DecimalFormat to convert the value to a string, then display that.
If you really want to round it to four digits, you can achieve that by multiplying by 10000, rounding, then dividing again. However, I would advise against it, since not all decimal numbers can be properly represented in floating point format. Changes are you'll just get something like you already had.
If you really want four digits to work with as an internal state, use a BigDecimal instead. It is properly equipped to do what you want.

How to get the numbers after the decimal point? (java) [duplicate]

This question already has answers here:
How do I get whole and fractional parts from double in JSP/Java?
(18 answers)
Closed 9 years ago.
double d = 4.321562;
Is there an easy way to extract the 0.321562 on it's own from d? I tried looking in the math class but no luck. If this can be done without converting to string or casting to anything else, even better.
Well, you can use:
double x = d - Math.floor(d);
Note that due to the way that binary floating point works, that won't give you exactly 0.321562, as the original value isn't exactly 4.321562. If you're really interested in exact digits, you should use BigDecimal instead.
Another way to get the fraction without using Math is to cast to a long.
double x = d - (long) d;
When you print a double the toString will perform a small amount of rounding so you don't see any rounding error. However, when you remove the integer part, the rounding is no longer enough and the rounding error becomes obvious.
The way around this is to do the rounding yourself or use BigDecimal which allows you to control the rounding.
double d = 4.321562;
System.out.println("Double value from toString " + d);
System.out.println("Exact representation " + new BigDecimal(d));
double x = d - (long) d;
System.out.println("Fraction from toString " + x);
System.out.println("Exact value of fraction " + new BigDecimal(x));
System.out.printf("Rounded to 6 places %.6f%n", x);
double x2 = Math.round(x * 1e9) / 1e9;
System.out.println("After rounding to 9 places toString " + x2);
System.out.println("After rounding to 9 places, exact value " + new BigDecimal(x2));
prints
Double value from toString 4.321562
Exact representation 4.321562000000000125510268844664096832275390625
Fraction from toString 0.3215620000000001
Exact value of fraction 0.321562000000000125510268844664096832275390625
Rounded to 6 places 0.321562
After rounding to 9 places toString 0.321562
After rounding to 9 places, exact value 0.32156200000000001448796638214844278991222381591796875
NOTE: double has limited precision and you can see representation issue creep in if you don't use appropriate rounding. This can happen in any calculation you use with double esp numbers which are not an exact sum of powers of 2.
Use modulo:
double d = 3.123 % 1;
assertEquals(0.123, d,0.000001);

Categories