Here you can find the source of safeDivide(long dividend, long divisor)
Parameter | Description |
---|---|
dividend | the dividend |
divisor | the divisor |
Parameter | Description |
---|---|
ArithmeticException | if the operation overflows or the divisor is zero |
public static long safeDivide(long dividend, long divisor)
//package com.java2s; /*//w ww . ja va 2s.c om * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.math.BigDecimal; import java.math.RoundingMode; public class Main { /** * Divides the dividend by the divisor throwing an exception if * overflow occurs or the divisor is zero. * * @param dividend the dividend * @param divisor the divisor * @return the new total * @throws ArithmeticException if the operation overflows or the divisor is zero */ public static long safeDivide(long dividend, long divisor) { if (dividend == Long.MIN_VALUE && divisor == -1L) { throw new ArithmeticException("Multiplication overflows a long: " + dividend + " / " + divisor); } return dividend / divisor; } /** * Divides the dividend by divisor. Rounding of result occurs * as per the roundingMode. * * @param dividend the dividend * @param divisor the divisor * @param roundingMode the desired rounding mode * @return the division result as per the specified rounding mode * @throws ArithmeticException if the operation overflows or the divisor is zero */ public static long safeDivide(long dividend, long divisor, RoundingMode roundingMode) { if (dividend == Long.MIN_VALUE && divisor == -1L) { throw new ArithmeticException("Multiplication overflows a long: " + dividend + " / " + divisor); } BigDecimal dividendBigDecimal = new BigDecimal(dividend); BigDecimal divisorBigDecimal = new BigDecimal(divisor); return dividendBigDecimal.divide(divisorBigDecimal, roundingMode).longValue(); } }