Domanda

Sto cercando di capire come per arrotondare un importo monetario verso l'alto alla 5 centesimi. Quanto segue mostra i miei risultati attesi

1.03     => 1.05
1.051    => 1.10
1.05     => 1.05
1.900001 => 1.10

devo il risultato di essere avere una precisione di 2 (come indicato sopra).

Aggiornamento

Seguendo i consigli di seguito, il meglio che potessi fare è questo

    BigDecimal amount = new BigDecimal(990.49)

    // To round to the nearest .05, multiply by 20, round to the nearest integer, then divide by 20
   def result =  new BigDecimal(Math.ceil(amount.doubleValue() * 20) / 20)
   result.setScale(2, RoundingMode.HALF_UP)

Non sono convinto che questo è kosher al 100% - mi riguarda la precisione potrebbe essere perso durante la conversione da e doppie. Tuttavia, è la migliore che è venuta in mente finora e sembra al lavoro.

È stato utile?

Soluzione

È possibile utilizzare doppio pianura per fare questo.

double amount = 990.49;
double rounded = ((double) (long) (amount * 20 + 0.5)) / 20;

EDIT: per i numeri negativi è necessario sottrarre 0.5

Altri suggerimenti

Utilizzando BigDecimal senza doppie (migliorato la risposta da marcolopes):

public static BigDecimal round(BigDecimal value, BigDecimal increment,
                               RoundingMode roundingMode) {
    if (increment.signum() == 0) {
        // 0 increment does not make much sense, but prevent division by 0
        return value;
    } else {
        BigDecimal divided = value.divide(increment, 0, roundingMode);
        BigDecimal result = divided.multiply(increment);
        return result;
    }
}

La modalità di arrotondamento è ad esempio RoundingMode.HALF_UP. Per i vostri esempi, in realtà si vuole RoundingMode.UP (bd è un aiutante, che restituisce solo new BigDecimal(input)):

assertEquals(bd("1.05"), round(bd("1.03"), bd("0.05"), RoundingMode.UP));
assertEquals(bd("1.10"), round(bd("1.051"), bd("0.05"), RoundingMode.UP));
assertEquals(bd("1.05"), round(bd("1.05"), bd("0.05"), RoundingMode.UP));
assertEquals(bd("1.95"), round(bd("1.900001"), bd("0.05"), RoundingMode.UP));

Si noti inoltre che c'è un errore nel tuo ultimo esempio (arrotondando 1,900001-1,10).

Mi piacerebbe provare moltiplicando per 20, arrotondando al numero intero più vicino, quindi dividendo per 20. Si tratta di un hack, ma dovrebbe ottenere la risposta giusta.

ho scritto questo in Java a pochi anni fa: https://github.com/marcolopes/dma/blob/master/org.dma.java/src/org/dma/java/math/BusinessRules.java

/**
 * Rounds the number to the nearest<br>
 * Numbers can be with or without decimals<br>
 */
public static BigDecimal round(BigDecimal value, BigDecimal rounding, RoundingMode roundingMode){

    return rounding.signum()==0 ? value :
        (value.divide(rounding,0,roundingMode)).multiply(rounding);

}


/**
 * Rounds the number to the nearest<br>
 * Numbers can be with or without decimals<br>
 * Example: 5, 10 = 10
 *<p>
 * HALF_UP<br>
 * Rounding mode to round towards "nearest neighbor" unless
 * both neighbors are equidistant, in which case round up.
 * Behaves as for RoundingMode.UP if the discarded fraction is >= 0.5;
 * otherwise, behaves as for RoundingMode.DOWN.
 * Note that this is the rounding mode commonly taught at school.
 */
public static BigDecimal roundUp(BigDecimal value, BigDecimal rounding){

    return round(value, rounding, RoundingMode.HALF_UP);

}


/**
 * Rounds the number to the nearest<br>
 * Numbers can be with or without decimals<br>
 * Example: 5, 10 = 0
 *<p>
 * HALF_DOWN<br>
 * Rounding mode to round towards "nearest neighbor" unless
 * both neighbors are equidistant, in which case round down.
 * Behaves as for RoundingMode.UP if the discarded fraction is > 0.5;
 * otherwise, behaves as for RoundingMode.DOWN.
 */
public static BigDecimal roundDown(BigDecimal value, BigDecimal rounding){

    return round(value, rounding, RoundingMode.HALF_DOWN);

}

Qui ci sono un paio di metodi molto semplici in C # ho scritto per arrotondare sempre su o giù per qualsiasi valore passato.

public static Double RoundUpToNearest(Double passednumber, Double roundto)
    {

        // 105.5 up to nearest 1 = 106
        // 105.5 up to nearest 10 = 110
        // 105.5 up to nearest 7 = 112
        // 105.5 up to nearest 100 = 200
        // 105.5 up to nearest 0.2 = 105.6
        // 105.5 up to nearest 0.3 = 105.6

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Ceiling(passednumber / roundto) * roundto;
        }
    }
    public static Double RoundDownToNearest(Double passednumber, Double roundto)
    {

        // 105.5 down to nearest 1 = 105
        // 105.5 down to nearest 10 = 100
        // 105.5 down to nearest 7 = 105
        // 105.5 down to nearest 100 = 100
        // 105.5 down to nearest 0.2 = 105.4
        // 105.5 down to nearest 0.3 = 105.3

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Floor(passednumber / roundto) * roundto;
        }
    }

In Scala Ho fatto la seguente (Java sotto)

import scala.math.BigDecimal.RoundingMode

def toFive(
   v: BigDecimal,
   digits: Int,
   roundType: RoundingMode.Value= RoundingMode.HALF_UP
):BigDecimal = BigDecimal((2*v).setScale(digits-1, roundType).toString)/2

E in Java

import java.math.BigDecimal;
import java.math.RoundingMode;

public static BigDecimal toFive(BigDecimal v){
    return new BigDecimal("2").multiply(v).setScale(1, RoundingMode.HALF_UP).divide(new BigDecimal("2"));
}

In base a tua modifica, un'altra soluzione possibile potrebbe essere:

BigDecimal twenty = new BigDecimal(20);
BigDecimal amount = new BigDecimal(990.49)

// To round to the nearest .05, multiply by 20, round to the nearest integer, then divide by 20
BigDecimal result =  new BigDecimal(amount.multiply(twenty)
                                          .add(new BigDecimal("0.5"))
                                          .toBigInteger()).divide(twenty);

Questo ha il vantaggio, di essere garantito di non perdere la precisione, anche se potrebbe potenzialmente essere più lento, naturalmente ...

E il resoconto della prova Scala:

scala> var twenty = new java.math.BigDecimal(20) 
twenty: java.math.BigDecimal = 20

scala> var amount = new java.math.BigDecimal("990.49");
amount: java.math.BigDecimal = 990.49

scala> new BigDecimal(amount.multiply(twenty).add(new BigDecimal("0.5")).toBigInteger()).divide(twenty)
res31: java.math.BigDecimal = 990.5

Per questo test per passare:

assertEquals(bd("1.00"), round(bd("1.00")));
assertEquals(bd("1.00"), round(bd("1.01")));
assertEquals(bd("1.00"), round(bd("1.02")));
assertEquals(bd("1.00"), round(bd("1.024")));
assertEquals(bd("1.05"), round(bd("1.025")));
assertEquals(bd("1.05"), round(bd("1.026")));
assertEquals(bd("1.05"), round(bd("1.049")));

assertEquals(bd("-1.00"), round(bd("-1.00")));
assertEquals(bd("-1.00"), round(bd("-1.01")));
assertEquals(bd("-1.00"), round(bd("-1.02")));
assertEquals(bd("-1.00"), round(bd("-1.024")));
assertEquals(bd("-1.00"), round(bd("-1.0245")));
assertEquals(bd("-1.05"), round(bd("-1.025")));
assertEquals(bd("-1.05"), round(bd("-1.026")));
assertEquals(bd("-1.05"), round(bd("-1.049")));

Cambia ROUND_UP in ROUND_HALF_UP:

private static final BigDecimal INCREMENT_INVERTED = new BigDecimal("20");
public BigDecimal round(BigDecimal toRound) {
    BigDecimal divided = toRound.multiply(INCREMENT_INVERTED)
                                .setScale(0, BigDecimal.ROUND_HALF_UP);
    BigDecimal result = divided.divide(INCREMENT_INVERTED)
                               .setScale(2, BigDecimal.ROUND_HALF_UP);
    return result;
}
  public static BigDecimal roundTo5Cents(BigDecimal amount)
  {
    amount = amount.multiply(new BigDecimal("2"));
    amount = amount.setScale(1, RoundingMode.HALF_UP);
    // preferred scale after rounding to 5 cents: 2 decimal places
    amount = amount.divide(new BigDecimal("2"), 2, RoundingMode.HALF_UP);
    return amount;
  }

Si noti che questo è fondamentalmente la stessa risposta Giovanni .

Tom ha l'idea giusta, ma è necessario utilizzare metodi BigDecimal, dal momento che si sta utilizzando apparentemente BigDecimal perché i valori non sono suscettibili di un tipo di dati primitivo. Qualcosa di simile:

BigDecimal num = new BigDecimal(0.23);
BigDecimal twenty = new BigDecimal(20);
//Might want to use RoundingMode.UP instead,
//depending on desired behavior for negative values of num.
BigDecimal numTimesTwenty = num.multiply(twenty, new MathContext(0, RoundingMode.CEILING)); 
BigDecimal numRoundedUpToNearestFiveCents
  = numTimesTwenty.divide(twenty, new MathContext(2, RoundingMode.UNNECESSARY));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top