Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    May 2001
    Messaggi
    64

    sottrazione con decimali problema

    Scusate , ma qualcuno sa dirmi perchè in javascript 1.6 - 1 non fa 0.6 ma 0.60000000000000001

    e se aete anche una spiegazione mi potreste consigliare come fare per avere risultati simili a quelli di un normale carlolatore cioe' 1.6 - 1 = 0.6
    grazie in anticipo

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    è un problema affrontato migliaia di volte su questo forum... ed è un problema di come la macchina computer rappresenta i numeri floating-point. Soluzione: decidi quanti decimali "esatti" vuoi e poi fai:

    codice:
    risultato = Math.round(risultato*Math.pow(10, numero_decimali_esatti))/Math.pow(10, numero_decimali_esatti);
    
    //Esempio:
    <html>
    <head>
    <script language="javascript">
    
    function fixDecimals(i,j) {
      return (Math.round(i*Math.pow(10,j))/Math.pow(10,j));
    }
    
    function test() {
      var i = 1.6 - 1;
      alert("Impreciso: "+i+"\n5 Cifre: "+fixDecimals(i,5));
    }
    </script>
    </head>
    <body onload="test();">
    </body>
    </html>
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.