Formatting Strings 0.2 to 2000 - java

How would one format the decimal number?
0.2 to show up as 2000.
I also want that even the value 0 would show up as 0000

Your question not really complete, if you want to show integer value of the decimal number (round up/down) then you just need to *10000 then round it, then format it as answered by RC .
public static void main(String[] args) {
float original = 0.2f;
float multiplied = original *10000;
int intvalue = (int)multiplied; // you can change to round up/down
String d = String.format("%04d", intvalue);
System.out.println("Value d : "+d);
}
Check here for the format https://dzone.com/articles/java-string-format-examples

This is the solution assuming that the desired output is 2000:
System.out.println(String.format("%.4f", 0.2).replaceFirst("^0\\.", ""));
Same for 0000:
System.out.println(String.format("%.4f", 0.0).replaceFirst("^0\\.", ""));
You could use a method for that:
private static String convert(double v) {
return String.format("%.4f", v).replaceFirst("^0\\.", "");
}

Related

converting from long to double with decimal point

I have some numbers as long type I want to convert it to double with specific decimal point figures.
public class Test
{
public static void main(String args[])
{
long l = 14253638;
DecimalFormat df = new DecimalFormat("00.0000");
System.out.println(df.format(l));
}
}
expected printed value : 14.2536
but actual printed value : 14253638.0000
We can do it via a BigDecimal:
long l = 1443156430;
BigDecimal bd = BigDecimal.valueOf(l).movePointLeft(4);
Results in:
144315.6430
To get it to a double:
double result = bd.doubleValue();
Note however that a BigDecimal may not be able to be represented precisely using a double.
EDIT: It's not very clear what precisely your requirements are - if it's a 2 digit number followed by 4 digits after the decimal point, then you can manipulate a string length:
String truncated = String.valueOf(l).substring(0, 6);
double result = new BigDecimal(truncated).movePointLeft(4).doubleValue();
This produces:
14.4315

Java/Android - set DecimalFormat to show only mantissa

I want to display only the mantissa of a number independently of what the exponent is.
12.4e-6 after formatting => 12.4
12.4e-12 after formatting => 12.4
To do the calculation manually is trivial. But the problem is that I need to use the class DeciamalFormat because I have to give it as argument to another class. I tried this:
DecimalFormat mFormat = (DecimalFormat) NumberFormat.getInstance();
mFormat.applyPattern("#.#E0");
if I remove the E symbol, the mantissa will not be calculated. is there any way using this DecimalFormat to show only mantissa?
Im pretty sure you cant, as what your asking is for DecimalFormat to show a different number than what you are representing
Why not apply DecimalFormat to return the String 12.4 then substring the portion in front of the e if you need String format? Or just multiply out based on the exponent?
To get 2 decimal places before the digits and one after you can do the following.
String s = String.format("%4.1f", d /
Math.pow(10, (int) (Math.log10(Math.abs(d)) - 1)));
Of course believing that the number after 999 => 99.9 is 1000 => 10.0 is just madness.
I have found following solution: I override the methods of the NumberFormat class so that I can manipulate how the Double values are transformed into Strings:
public class MantissaFormat extends NumberFormat {
#Override
/** Formats the value to a mantissa between [0,100] with two significant decimal places. */
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
String output;
String sign="";
if(!isFixed)
{
if(value<0)
{
sign = "-";
value = -value;
}
if(value!=0) {
while(value<1) {
value *= 100;
}
while(value>100){
value/=100;
}
}
}
// value has the mantissa only.
output = sign + String.format( "%.2f", value );
buffer.append(output);
return buffer;
}
#Override
public Number parse(String string, ParsePosition position) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}

Java Double get all Digits after dot/comma

it´s a simple task but i´m not able to solve it on my own..
i got
double digit1 = 12.1;
double digit2 = 12.99;
and need a method which gives me this:
anyMethod(digit1); //returns 10
anyMethod(digit2); //returns 99
what i have is
public static void getAfterComma(double digit) {
BigDecimal bd = new BigDecimal(( digit - Math.floor( digit )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println(bd.toBigInteger()); // prints digit1=1 and digit2=99
}
anyway i prefer integer as the returntype..
anybody got a quick solution/tip?
kindly
Why not you simply use:
int anyMethod(double a){
//if the number has two digits after the decimal point.
return (int)((a + 0.001) * 100) % 100;
}
A simple way of getting the fractional part of a double is to use the modulo operator, %. However, you'll have to take into account the fact that floating point arithmetic isn't precise. For example,
System.out.println(12.1 % 1); // outputs 0.09999999999999964
System.out.println(12.99 % 1); // outputs 0.9900000000000002
If you want to get two decimal digits as an int, which is what I think you're asking, you can achieve this, glossing over the floating point issues, like so:
System.out.println(Math.round((12.1 % 1) * 100)); // outputs 10
System.out.println(Math.round((12.99 % 1) * 100)); // outputs 99
However, you should consider going further down the BigDecimal path you started down, which uses arbitrary precision arithmetic. You could do something like this:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE)); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE)); // outputs 0.99
If, as before, you want two decimal digits from this, you can do this:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.99
Note that there a couple of differences between these last two methods and the first two: they preserve the sign of the argument, so if you use the final example for -12.99, you'll get -99 back, and they treat the fractional part of an integer as 1, so if you use the final example for 12, you'll get 100 back.
It's not necessary to use Number tyeps all the time. You can take advantage of String as a mediator.
String mediator = Double.valueOf(d1).toString();
mediator = mediator.substring(mediator.indexOf('.') + 1);
Integer result = Integer.valueOf(mediator);
Try this out
public static void main(String args[]){
double a=12.99;
double b=12.1;
System.out.println(method(a));
System.out.println(method(b));
}
private static int method(double a) {
return (int) ((a*100)%100);
}
sachin-pasalkar done it! little fix but fine!
public static int anyMethod(double a){
return (int) (a*100)%100;
}
check out this code returns digits after '.' always. Without any extra parameters other than double variable.
public int anyMethod(double d)
{
String numString = d+"";
return Integer.parseInt(numString.substring(numString.indexOf('.')+1));
}
If I understand correctly, you need to return n digits after the dot for a given double number. So... let's see:
public int decimalDigits(double x, int n) {
double ans;
ans = (x - (int) x) * Math.pow(10, n);
return (int) ans;
}
Done. Hope this helps you.
For your specific example, 'n = 2' should do.

Remove leading zero and delimiter char for BigDecimal

Our application can get following numbers:
0.1
0.02
0.003
etc.
These values treated by our code as BigDecimal,as far we operate with money.
There is form on web UI, where user should view these floating parts of prices, transformed to following ones:
1
02
003
The question is,how to trim leading zero and delimiter character in input prices. Perhaps BigDecimal class has standard method something like trimLeadingZeroes(),but can't find any.
UPDATE:
trim just leading zero and delimiter symbol
For instance:
1 is 0.1
27 is 0.27
Something like this?
public String getDecimalFractions(BigDecimal value) {
String strValue = value.toPlainString();
int index = strValue.indexOf(".");
if(index != -1) {
return strValue.substring(index+1, strValue.length());
}
return "0";
}
Have you tried calling BigDecimal.unscaledValue? The downside is that 0.13 would then be 13 whereas you possibly want 1.3... it's slightly hard to tell. If you could give more examples, that would really help.
(That approach would also fail if the value were 1000 to start with - you'd end up with 1...)
Could it be something as simple as doing this:
public static BigDecimal fix(String str){
return new BigDecimal("0." + str);
}
so if you make
public static void main(String[] args) {
System.out.println(fix("1"));
System.out.println(fix("02"));
System.out.println(fix("003"));
}
It will print
0.1
0.02
0.003
when ever you have to deal with splitting something its a good bet Strings can be used for it.
You first just convert the bigdecimal into a string
String s=bd.toPlainString();
Then you simply split it as so
String s2=s.split("\\.")[1];
now String s2 contains the numbers after the delimiter
Conversion from BigDecimal to String:
import java.math.BigDecimal;
public class XXX {
public static void main(String[] args){
doIt("123");
doIt("123.1");
doIt("123.01");
doIt("123.0123");
doIt("123.00123");
}
static void doIt(String input){
BigDecimal bdIn = new BigDecimal(input);
System.out.println(bdIn+" -> "+convert(bdIn));
}
static String convert(BigDecimal bdIn) {
BigDecimal bdOut = bdIn.subtract(bdIn.setScale(0, BigDecimal.ROUND_DOWN));
return bdOut.signum() == 0 ? "0" : bdOut.toPlainString().substring(2);
}
}
Results are:
123 -> 0
123.1 -> 1
123.01 -> 01
123.0123 -> 0123
123.00123 -> 00123
The code works directly with any number and takes into account only the fractional part.
It also handles "0.0" gracefully.
Is this the conversion you wanted?
Here is another simple way of doing this - assuming your input is 1.023456
BigDecimal bd = new BigDecimal("1.023456");
BigInteger bi = bd.toBigInteger();
BigDecimal bd2 = bd.subtract(new BigDecimal(bi));
String afterDecimalPoint = bd2.scale() > 0 ?
bd2.toString().substring(2) : "";
This will give the exact result as you were looking for in bd3, i.e. it'll be 023456 for the above example.
It'll work ok for whole numbers too, due to the condition in last line, i.e. 1 will return ""
You could use the string representation of value (a BigDecimal) and StringUtils.substringAfter to do this:
StringUtils.substringAfter(value.toPlainString(), ".")
How about writing an extension method to extend this type. Simple method might multiply number until > 1
public int trimLeadingZeroes(bigint num) {
while (num < 1)
{
num = num * 10;
}
return num;
}
import java.math.BigDecimal;
import java.math.RoundingMode;
public class RemoveZeroes {
static final int SCALE = 10; // decimal range 0.1 ... 0.0000000001
static final String PADDING = "0000000000"; // SCALE number of zeroes
public static void main(String [] arg) {
BigDecimal [] testArray = {
new BigDecimal(0.27),
new BigDecimal(0.1),
new BigDecimal(0.02),
new BigDecimal(0.003),
new BigDecimal(0.0000000001),
};
for (int i = 0; i < testArray.length; i++) {
// normalize to the same scale
BigDecimal b = testArray[i].setScale(SCALE, RoundingMode.FLOOR);
// pad on the left with SCALE number of zeroes
String step1 = PADDING + b.unscaledValue().toString();
// remove extra zeroes from the left
String step2 = step1.substring(step1.length() - SCALE);
// remove extra zeroes from the right
String step3 = step2.replaceAll("0+$", "");
// print result
System.out.println(step3);
}
}
}

How do I round a double to two decimal places in Java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 3 years ago.
This is what I did to round a double to 2 decimal places:
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.
Just use: (easy as pie)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
The output will be 651.52
Are you working with money? Creating a String and then converting it back is pretty loopy.
Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.
Even if you're not working with money, consider BigDecimal.
Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:
DecimalFormat twoDForm = new DecimalFormat("#.00");
Use this
String.format("%.2f", doubleValue) // change 2, according to your requirement.
You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.
This is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.
double total = 1.4563;
total = Math.round(total * 100);
System.out.println(total / 100);
The result is 1.46.
You can use org.apache.commons.math.util.MathUtils from apache common
double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);
double amount = 25.00;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(amount));
You can use Apache Commons Math:
Precision.round(double x, int scale)
source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)
Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.
Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).
public static Double round(Number src, int decimalPlaces) {
return Optional.ofNullable(src)
.map(Number::doubleValue)
.map(BigDecimal::new)
.map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
.map(BigDecimal::doubleValue)
.orElse(null);
}
You can try this one:
public static String getRoundedValue(Double value, String format) {
DecimalFormat df;
if(format == null)
df = new DecimalFormat("#.00");
else
df = new DecimalFormat(format);
return df.format(value);
}
or
public static double roundDoubleValue(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.
private static DecimalFormat df2 = new DecimalFormat("#.00");
Now, apply the format to your double value:
double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12
Note in case of double input = 32.1;
Then the output would be 32.10 and so on.
If you want the result to two decimal places you can do
// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0;
This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)
Math.round is one answer,
public class Util {
public static Double formatDouble(Double valueToFormat) {
long rounded = Math.round(valueToFormat*100);
return rounded/100.0;
}
}
Test in Spock,Groovy
void "test double format"(){
given:
Double performance = 0.6666666666666666
when:
Double formattedPerformance = Util.formatDouble(performance)
println "######################## formatted ######################### => ${formattedPerformance}"
then:
0.67 == formattedPerformance
}
Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
if (d < 0)
d -= 0.005;
else if (d > 0)
d += 0.005;
return (double)((long)(d * 100.0))/100);
}
where num is the double number
Integer 2 denotes the number of decimal places that we want to print.
Here we are taking 2 decimal palces
System.out.printf("%.2f",num);
Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
The result is: 98765.43
int i = 180;
int j = 1;
double div= ((double)(j*100)/i);
DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
System.out.println(div);
System.out.println(df.format(div));
You can use this function.
import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
String rightPad = StringUtils.rightPad("1", c+1, "0");
int decimalPoint = Integer.parseInt(rightPad);
number = Math.round(number * decimalPoint);
return number/decimalPoint;
}

Categories

Resources