Advertisement
Muk99

Fração

Aug 13th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. static class Fraction {
  4.  
  5.     //Numero maximo de vezes que o while vai rodar, se deixar muito grande fica pesado e se deixar infinito PODE travar
  6.     private const int maxItr = 1500;
  7.  
  8.     //Função pra mandar em fração
  9.     public static string ToFraction(this float value) {
  10.  
  11.         //Valor de cima da fração
  12.         var upValue = value;
  13.         //Valor de baixo
  14.         var downValue = 1;
  15.  
  16.         //Enquanto o valor de cima tiver virgula...
  17.         while(!Mathf.Approximately(upValue, Mathf.Ceil(upValue))) {
  18.             //Adiciona mais o valor no valor de cima
  19.             upValue += value;
  20.             //E aumenta o valor de baixo
  21.             downValue++;
  22.  
  23.             //Se passar de 1500 vezes retorna o valor pq a fração vai ficar zoada
  24.             if(downValue > maxItr)
  25.                 return value.ToString();
  26.         }
  27.  
  28.         //Se o valor de baixo for 1 ele é desnecessário
  29.         if(downValue == 1)
  30.             return value.ToString();
  31.  
  32.         //Retorna a string bonitinha
  33.         return upValue + "/" + downValue;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement