You could create a CustomBigDecimal that extends from BigDecimal. However, as BigDecimal is immutable, you would never inherit state (such as the scale and rounding mode) from the parent class. I'd go for the utility class suggested in another answer, or maybe a wrapper that delegates every operation to an...

I found the solution to this issue some time ago,forgot to come back. It was kind of a mistake on my part.Kind of. The user application was making the calculus somewhere,sending it to the database then i was extracting it and redoing the calculus in another application(with the same calculus...

Give annotation to amount field of Item class as follows class Item { @Digits(integer=6, fraction=2, message="{javax.validation.constraints.Digits.message}") private BigDecimal amount; } In the above class integer and fraction are compulsory and message is optional parameter to @Digit and there we can configure custom error message. Now, we create a properties file...

You can look at source code. public BigDecimal(int val) { intCompact = val; } public BigDecimal(String val) { this(val.toCharArray(), 0, val.length()); } public BigDecimal(char[] in, int offset, int len) { ...very long } Obviously, who is faster....

I think that this is actually the correct rounding using the scale of 2 and the RoundingMode HALF_UP. The Javadocs for BigDecimal define ROUND_HALF_UP to do the following: Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if...

Because BigDecimal is immutable you have to assign the result of the call to setScale() to c, c = c.setScale(2, RoundingMode.HALF_UP); the linked Javadoc says (in part) Returns a BigDecimal whose scale is the specified value. tl;dr It doesn't modify c in place....

ruby-on-rails,ruby,bigdecimal,zero,number-to-currency

That is so because the number is converted into a string to be displayed. And: # to_d converts to BigDecimal, just FYI "-0".to_d.to_s #=> "-0.0" Therefore you will have to make it a 0 yourself. But the sign-checks are redundant - a simple comparison with 0 will do the trick:...

java,rounding,bigdecimal,divide

It all has to do with the scales of the BigDecimals involved. When you specify exponential format in the constructor that takes a String, the scale may be negative. This indicates that the significant digits don't extend all the way down to unity. BigDecimal oneEPlus8 = new BigDecimal("1.0E+8"); System.out.println(oneEPlus8.scale()); This...

java,precision,biginteger,bigdecimal,largenumber

Using BigDecimal and doing calculation in double is the same as not using BigDecimal at all. Use BigDecimal to do calculations: BigDecimal bigNumber = new BigDecimal(1000).pow(10); System.out.println(bigNumber); ...

"How does the round work? I want to take in consideration only the value of the second decimal." It sounds like you want to truncate instead of round. Instead of using ROUND_HALF_DOWN: Rounding mode to round towards "nearest neighbor"... ...instead, try using ROUND_DOWN: Rounding mode to round towards zero....

Try BigDecimal TAX_RATE = new BigDecimal("1").divide(new BigDecimal("11"), 500, BigDecimal.ROUND_HALF_UP); Second argument specifies precision. It's zero by default, so you end up rounding everything to an int....

Did you already crawl through JavaDoc, especially the function precision()? And this here might be a direct solution which makes it needless to check the precision first: yournumber.round(new MathContext(5, HALF_UP)); And after that use stripTrailingZeros() (thx to @GregKopff)...

If I understand you, you've missed the assignment from the result of setScale(); d = d.setScale(4); Edit As for your second question, you can call stripTrailingZeros() - d = d.stripTrailingZeros(); ...

ruby,precision,equality,bigdecimal

I reported the bug to the Ruby core team. However, this is not a bug as you can see in the rejection response. BigDecimal, though offers arbitrary precision, cannot represent numbers like 1/3 precisely. Thus during some arithmetic you can encounter imprecisions. You can use Rational in Ruby for exact...

The problem is you have a value which can't be represented in double but nor can it be represented in BigDecimal so you have to apply reasonable rounding to get the expected solution. double d = 60 / 1.1 * 1.1; System.out.println("double without rounding: " + d); System.out.printf("double With rounding...

android,android-activity,bigdecimal

Apparently in my XML file I put the underline tags around 0.00 which gives the error when it is being converted to BigDecimal.. I removed the tags and everything works now

You can't add BigDecimal with +, you have to use its add() function. It is also immutable, so using the same BigDecimal sum for the whole addition won't work. BigDecimal isn't just another class for numbers like Integer and Double are....

try to compile and run this java class, it works as you wish: import java.math.*; class decimal { public static void main(String[] args) { BigDecimal result = new BigDecimal(0); BigDecimal v1 = new BigDecimal(10); BigDecimal v2 = new BigDecimal(3); result = v1.divide(v2,2,BigDecimal.ROUND_HALF_UP); System.out.println(result); } } output : 3.33 you want...

A simplified solution could be (pseudo code) if (multiple == 0.1) then { output = input } else { if ((int) input * 10 % 2 == 1) { output -= 0.1 } else { output = input } } You need to take care about the rounding after you...

Use setScale() to trim off everything after 2 decimal points, and compareTo() to see if it's mathematically equal to the original value: class BigDecimalExperiment { static boolean isEverythingAfterTwoDigitsZero(BigDecimal bd) { return (bd.compareTo(bd.setScale(2, RoundingMode.DOWN)) == 0); } public static void main(String[] args) { List<BigDecimal> values = Arrays.asList( new BigDecimal("7.5"), new BigDecimal("7.50000"),...

This is explained in the javadoc for the BigDecimal(double) constructor: The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is...

"#<BigDecimal:6fe4790,'0.1E2',9(36)>"[/(?<=').+(?=')/] # => "0.1E2" ...

From El 3.0 spec pdf (page 13 - section 1.7.1): The evaluation of arithmetic operators is described in the following sections. A and B are the evaluation of subexpressions. 1.7.1 Binary operators - A {+,-,*} B If A and B are null, return (Long)0 If A or B is a...

ParseBigDecimal (prior to 2.2.0) only uses the decimal separator from the supplied DecimalFormatSymbols (not the grouping separator). It's not a bug, just a limitation of the current implementation. You can chain a StrReplace before the ParseBigDecimal (i.e. replace "." with "") and that should fix your problem (quickly). I think...

You get an ArithmeticException as described in BigDecimal.divide(BigDecimal) - "if the exact quotient does not have a terminating decimal expansion" because to properly represent the result of 1/3 would take infinite memory. By using BigDecimal.divide(BigDecimal,int,RoundingMode) you explicitly set what precision you'll tolerate, meaning any division can be approximated in-memory. For...

java,string,decimal,bigdecimal,scientific-notation

If you look at the toString() function of BigDecimal, it explains how the output is created: Next, an adjusted exponent is calculated; this is the negated scale, plus the number of characters in the converted unscaled value, less one. That is, -scale+(ulength-1), where ulength is the length of the absolute...

This is by definition. From BigDecimal's javadoc: The exponent consists of the character 'e' ('\u0065') or 'E' ('\u0045') followed by one or more decimal digits. The value of the exponent must lie between -Integer.MAX_VALUE (Integer.MIN_VALUE+1) and Integer.MAX_VALUE, inclusive. Emphasis by me, and Integer.MAX_VALUE = 2147483647....

As seen in the comments: there is a problem with the calculation of frac1 and frac2. Before creating a BigDecimal you are doing a double-division. Try: frac1 = new BigDecimal(21, mtCtx).divide(new BigDecimal(231, mtCtx), mtCtx); frac2 = new BigDecimal(210, mtCtx).divide(new BigDecimal(231, mtCtx), mtCtx); ...

java,double,classcastexception,bigdecimal,jspinner

This program illustrates conversion in both directions between Double and BigDecimal: import java.math.BigDecimal; public class Test { public static void main(String[] args) { Double d1 = 1.3; BigDecimal bd1 = BigDecimal.valueOf(d1.doubleValue()); Double d2 = bd1.doubleValue(); System.out.println(d2); } } Note that the conversion to Double may not be exact....

Both your questions are clearly stated in the Javadoc. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually...

java,decimal,bigdecimal,divide

You can do it like that: Double result=Double.parseDouble(s_dd + "." + s_mm); NumberFormat formatter = new DecimalFormat("#0.000000"); return formatter.format(result); ...

Try this str = str.replaceFirst("^0\\.", "."); ...

In your code when you are changing rounding methods, you are passing already rounded value to next step. For example, value was rounded by HALF_EVEN to two places and then this already rounded value (2 places) is being passed to FLOOR step and so on. To get behavior you are...

According to Wikipedia (http://en.wikipedia.org/wiki/Rounding#Rounding_to_a_specified_increment), rounding a number x to a multiple of some increment m requires the following procedure: Rounded value z = round(x, m) = round(x / m) * m In your case, you want to always round down. This is achieved by using floor instead of round. Translated...

Change Doubles to BigDecimals Look at the constructor BigDecimal(String) double val = 5.2; BigDecimal bd = new BigDecimal(String.valueOf(val)); System.out.println(bd); Explore other constructors also of BigDecimal....

How about using substring instead? It's not really a number anyway. int pos = x.indexOf('.'); String y = x.substring(pos - 12, pos + 3); If you are really crazy enough to try processing this as numbers (collissions and differences in rounding are going to break your neck sooner or later!),...

String result = String.format("%013.2f", invoice.getAmount()); Note that the symbol used for the decimal point is locale-specific; you might for example get , instead of .. If you need it to always be dot . then specify a locale for which the decimal point is a dot, for example: String result...

The important part of the #setScale documentation is this: Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper...

java,integer,currency,bigdecimal,money

Try this code: BigDecimal db = new BigDecimal("49.99"); // multiply with 10^scale ( in your case 2) db = db.multiply(new BigDecimal(10).pow( db.scale())); System.out.println(db.intValue()); ...

java,scale,bigdecimal,scientific-notation

If I understand you correctly, d = d.setScale(0) will work: BigDecimal d = BigDecimal.valueOf(1e3).setScale(-3); System.out.println(d.unscaledValue()); d = d.setScale(0); System.out.println(d.unscaledValue()); Output is: 1 1000 Note that BigDecimal is immutable, thus you have to reassign it....

I think you have a 2 part problem: BigDecimal - requires a precision if you don't want it to round to an integer, so BigDecimal(1.7,1) is 2 and BigDecimal(1.7,2) is 1.7 The datatypes on the withdraw and deposit fields may be integer and not decimal ...

ruby-on-rails,ruby,activerecord,sqlite3,bigdecimal

Unless absolutely required, don't use instance variables in the class method that you've defined. There's a good chance that at least one of those instance variables isn't properly set when you call the method. Subsequently, your database row isn't updated. Either pass the object and new value to the method...

Uhh, 0.575306 - 0.574716 is in fact 0.00059. ...

java,rounding,bigdecimal,arithmeticexception

Use either RoundingMode.DOWN or RoundingMode.FLOOR. BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN); ...

Prior to Java 8, it would be: public static void main(String[] args) { HashMap<String, BigDecimal> bd_map = new HashMap<>(); bd_map.put("Shirts", BigDecimal.ZERO); bd_map.put("Hats", BigDecimal.ZERO); bd_map.put("Shoes", BigDecimal.ZERO); bd_map.put("Shirts", bd_map.get("Shirts").add(new BigDecimal("5.99"))); bd_map.put("Shirts", bd_map.get("Shirts").add(new BigDecimal("4.50"))); bd_map.put("Shoes", bd_map.get("Shoes").add(new BigDecimal("15.99"))); bd_map.put("Hats", bd_map.get("Hats").add(new BigDecimal("8.00")));...

You're computing pi as a double and then converting it to BigDecimal. That won't magically add more precision than was in the double, which by definition can't be more than 53 bits. You need to do the computation of pi in BigDecimal....

You can use DecimalFormat setMinimumFractionDigits and set it to the same as the maximum.

How about multiplying by 100. String text = String.format("%06.0f", Double.parseDouble("275.1234")*100); or String text = String.format("%06.0f", 275.1234 * 100); or String text = String.format("%06.0f", BigDecimal.valueOf(275.1234).doubleValue() * 100); sets text to 027512 If you want to truncate rather than round you can do String text = String.format("%06d", (long) (1234.5678 * 100)); prints...

java,integer,type-conversion,bigdecimal

The simplest which includes my points below is: public static int usdToCents(BigDecimal usd) { return usd.movePointRight(2).intValueExact(); } Yours is OK, but I would still do this: private static final BigDecimal x100 = new BigDecimal(100); public static int usdToCents(BigDecimal usd) { BigDecimal rounded = usd.setScale(2, BigDecimal.ROUND_CEILING); BigDecimal bigDecimalInCents = rounded.multiply(x100); int...

I think the BigDecimal.java best explains this feature. API say's Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer. Notes: The results of...

No, you appear to have a legit bug. The bug presents in JDK7 but fixed in JDK8. Your values are correctly representable as BigDecimals, and should behave correctly, but don't. Tracing through the source code of BigDecimal, on line 2585, this.precision() is 1, and this.scale is -2147483647. this.precision() - this.scale...

java,exception,number-formatting,bigdecimal

It's by design. See javadoc: Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. If this rounding mode is specified on an operation that yields an inexact result, an {@code ArithmeticException} is thrown. This mode is made to specifically throw an exception...

Apart from decimal format you can also use setScale(2) like this new BigDecimal("1.0000").setScale(2) Also setScale allows you can specify the Rounding Mode ...

An improvement i can see is to attempt to use a factory pattern along with Polymorphism. Have an interface called:CurrencyFX Have for each currency its own class, example : GBPCurrencyFX Then have the factory return an instance of the currency you want to calculate. Remember, each class will have all...

You can use the constructor with String parameter. BigDecimal d=new BigDecimal("1"); System.out.println(d.toString());//Will print 1 BigDecimal d=new BigDecimal("1.1"); System.out.println(d.toString()); //Will print 1.1 BigDecimal d=new BigDecimal("2.50"); System.out.println(d.toString()); //Will print 2.50 ...

java,bigdecimal,parseexception

Instead of dealing with the parsing yourself you could make use of the BigDecimal(String val) constructor. From the Javadoc BigDecimal(String val) Translates the string representation of a BigDecimal into a BigDecimal For example: BigDecimal bigDecimal = new BigDecimal("86400864008640086400222"); See the Javadoc for the formats the constructor takes....

and it works as if I ever didn't put the scale into getBonusSum(). For instance: Because newBonus.getBonusSum().setScale(0) returns a new BigDecimal objectWhen you invoke setScale method it returns a new BigDecimal object and it doesn't modify the existing object. So you need to re-assign it to newBonus like this...

I'm pretty sure this is not the best way, but it's one way. First note that if your numbers have more than six digits before the period, or more generally more than width - 2 digits before the period, your format with .0 will not work anymore. String.format() uses half...

r,long-integer,biginteger,bigdecimal

All your problems can be solved with Rmpfr most likely which allows you to use all of the functions returned by getGroupMembers("Math") with arbitrary accuracy. Vignette: http://cran.r-project.org/web/packages/Rmpfr/vignettes/Rmpfr-pkg.pdf Simple example of what it can do: test <- mpfr(rnorm(100,mean=0,sd=.0001), 240) Reduce("*", test) I don't THINK it has hypergeometric functions though......

Use the standard approach of divide, round, multiply private static BigDecimal round(BigDecimal input, int multiple) { return input.divide(new BigDecimal(multiple)) .setScale(0, RoundingMode.CEILING) .multiply(new BigDecimal(multiple)); } for (double i = 0; i < 10; i += 0.9) { System.out.println(String.format("%.1f => %s", i, round(new BigDecimal(i), 5))); } Output 0.0 => 0 0.9 =>...

java,comparison,biginteger,bigdecimal

For BigInteger and BigDecimal you should use the compareTo method to check if their value is the same System.out.println(new BigDecimal(BigInteger.valueOf(10)).compareTo(BigDecimal.valueOf(10.0))); ...

The divide method of BigDecimal lets you specify the scale of the result, which loosely speaking is number of decimal places. scale = 3 means that a number will be expressed with 3 decimal places. A negative scale indicates the number of insignificant zeroes at the end of a whole...

Try like this: BigDecimal value = new BigDecimal(123); value = value.setScale(2, BigDecimal.ROUND_HALF_EVEN) You can refer Javadocs for ROUND_HALF_EVEN and setScale...

I strongly recommend using the Joda-Money library for working with money, rather than trying to reinvent the wheel yourself. Working with money is a common, and tricky, problem. Let other people solve it for you. It's always a little frustrating to add a new dependency to your project, but when...

In your code you are only calling reverse which reverses the order of the list. You need to sort the list as well, in reversed order. This will do the trick: Collections.sort(list, Collections.reverseOrder()); ...

Your assertion is saying "does this object equal this other object". It appears you want to compare values. You can do that like so: [4] pry(main)> BigDecimal('144.50') == 144.50 => true That would make your test look something like: assert_equal 144.50, actual_value where actual_value is coming from the database....

You are doing conversion to double and backwards. That's unnecessary and introduces rounding errors. You should use the following code: private BigDecimal loadBigDecimal(String value) throws ParseException { DecimalFormat df = new DecimalFormat("##.###"); df.setParseBigDecimal(true); return (BigDecimal) df.parse(value); } ...

It looks to me like the Object ID is changing, but not the value; all of the results you list use the format #<BigDecimal:xxxxxxx,'0.9E0',9(36)> Each time you reload the page, Rails is creating a new BigDecimal object instance, but with the same data in it. Here's a similar example, using...

java,bigdecimal,arbitrary-precision,numeric-precision

You have confused scale (total number of decimal places) with precision (number of significant digits). For numbers between -1 and 1, the precision does not count any zeroes between the decimal point and the non-zero decimal places, but the scale does. The second argument to BigDecimal.divide is a scale. So...

I found a simple solution. It doesn't need to do stripTrailingZeros() in the getter method. Just public BigDecimal getValue() { return value; } And on the JSP <fmt:formatNumber value="${object.value}" minFractionDigits="0"/> ...

You are not performing the same operations. When you are doing the double operations, the normal java order of operations is applying: a-a/1.05 = a - (a/1.05) But when you are running the methods on BigDecimal, the operations are evaluated in the order you are calling them, so b.subtract(b).divide(new BigDecimal(1.05))...