Traduzido automaticamente do inglês, que é a versão original.
Campos e métodos de number
Números inteiros e decimais.
Um número é escrito como se lê: 42, 3.5, -7. Números inteiros permanecem exatos por maior que fiquem, então 2 ** 100 mostra todos os dígitos, e números com ponto decimal funcionam com cerca de 15 algarismos significativos.
Os métodos de número devolvem um novo número e nunca alteram uma variável, então guarde o resultado: $total = $total->round(digits: 2).
Um sinal de menos escrito colado a um número faz parte dele, então -5->abs() é 5. Com uma variável, o sinal se aplica à cadeia inteira: -$change->abs() é o negativo do tamanho da mudança, e (-$change)->abs() primeiro agrupa a expressão entre parênteses.
Para verificar se um número está dentro de um intervalo, encadeie comparações como na matemática. Ambos os extremos contam com <=:
<let name="age" value="18" />
<echo value="13 <= $age <= 19" /> <!-- true because 18 is a teenage age -->
<echo value="0 <= $age <= 17" /> <!-- false because 18 is past 17 -->
$age = 18
echo 13 <= $age <= 19 // true because 18 is a teenage age
echo 0 <= $age <= 17 // false because 18 is past 17
Um campo é um dado simples sobre o valor, lido com um ponto e sem colchetes: $value.name. Um método recebe argumentos ou executa alguma ação, e é chamado com ->: $value->name(arguments), ou com o valor passado por pipe: $value |> name(arguments).
->abs() retorna o número sem o sinal de menos: a distância dele até zero. Serve para uma diferença em que você se importa com o tamanho, mas não com o sentido:
<let name="change" value="4 - 9" />
<echo value="$change" /> <!-- -5 -->
<echo value="$change->abs()" /> <!-- 5 because the sign is dropped -->
<echo value="-5->abs()" /> <!-- 5 because -5 is one number, and its size is 5 -->
$change = 4 - 9
echo $change // -5
echo $change->abs() // 5 because the sign is dropped
echo -5->abs() // 5 because -5 is one number, and its size is 5
Atua sobre os bits do número, como inteiro: and: mantém os bits que os dois têm (12->bits(and: 10) é 8), or: os bits que pelo menos um tem (15), xor: os bits que apenas um tem (6), shift: desloca para a esquerda, ou para a direita quando negativo (1->bits(shift: 4) é 16), e invert inverte todos os bits (5->bits(invert) é -6). Um de cada vez.
->bits(and|or|xor|shift: number) ou ->bits(invert) atua sobre os dígitos binários de um inteiro, um passo por chamada. Serve para flags empacotadas em um só número, em que cada bit significa uma coisa:
<let name="read" value="4" />
<let name="write" value="2" />
<let name="permissions" value="6" /> <!-- read and write, because 4 + 2 is 6 -->
<echo value="$permissions->bits(and: $read) == $read" /> <!-- true because 6 has the 4 bit set -->
<echo value="$permissions->bits(or: 1)" /> <!-- 7 because or: turns the 1 bit on -->
<echo value="$permissions->bits(xor: $write)" /> <!-- 4 because xor: flips the 2 bit off -->
<echo value="$permissions->bits(shift: 1)" /> <!-- 12 because every bit moves one place left -->
<echo value="$permissions->bits(shift: -1)" /> <!-- 3 because a negative shift moves right -->
<echo value="$permissions->bits(invert)" /> <!-- -7 because every bit flips -->
$read = 4
$write = 2
$permissions = 6 // read and write, because 4 + 2 is 6
echo $permissions->bits(and: $read) == $read // true because 6 has the 4 bit set
echo $permissions->bits(or: 1) // 7 because or: turns the 1 bit on
echo $permissions->bits(xor: $write) // 4 because xor: flips the 2 bit off
echo $permissions->bits(shift: 1) // 12 because every bit moves one place left
echo $permissions->bits(shift: -1) // 3 because a negative shift moves right
echo $permissions->bits(invert) // -7 because every bit flips
->ceil() arredonda para o próximo inteiro, ou mantém um inteiro como está. Serve para contar quantos itens são necessários para caber tudo:
<let name="people" value="23" />
<echo value="($people / 4)->ceil()" /> <!-- 6 because 23 / 4 is 5.75, and 5 tables of 4 would leave 3 people standing -->
<echo value="6->ceil()" /> <!-- 6 because it is already whole -->
<echo value="-2.5->ceil()" /> <!-- -2 because up means towards the larger number -->
$people = 23
echo ($people / 4)->ceil() // 6 because 23 / 4 is 5.75, and 5 tables of 4 would leave 3 people standing
echo 6->ceil() // 6 because it is already whole
echo -2.5->ceil() // -2 because up means towards the larger number
->clamp(min, max) mantém o número dentro de min..max. Abaixo de min retorna min, acima de max retorna max, e entre os dois retorna o próprio número:
<echo value="150->clamp(0, 100)" /> <!-- 100 because 150 is above the top -->
<echo value="-20->clamp(0, 100)" /> <!-- 0 because -20 is below the bottom -->
<echo value="42->clamp(0, 100)" /> <!-- 42 because it is already in range -->
echo 150->clamp(0, 100) // 100 because 150 is above the top
echo -20->clamp(0, 100) // 0 because -20 is below the bottom
echo 42->clamp(0, 100) // 42 because it is already in range
->floor() arredonda para baixo, até o inteiro anterior, ou mantém um inteiro como está. Serve para contar quantos itens inteiros cabem:
<let name="budget" value="20" />
<echo value="($budget / 3)->floor()" /> <!-- 6 because 20 / 3 is 6.67, and only 6 whole tickets at £3 fit in £20 -->
<echo value="3.99->floor()" /> <!-- 3 because the decimals are always dropped downwards -->
<echo value="-2.5->floor()" /> <!-- -3 because down means towards the smaller number -->
$budget = 20
echo ($budget / 3)->floor() // 6 because 20 / 3 is 6.67, and only 6 whole tickets at £3 fit in £20
echo 3.99->floor() // 3 because the decimals are always dropped downwards
echo -2.5->floor() // -3 because down means towards the smaller number
Formata o número (formato .NET, N0 por padrão: 1,234).
->format(pattern?) transforma o número em texto para ser lido por pessoas. Sem padrão, retorna um inteiro com vírgulas separando os milhares. Um padrão escolhe outro formato: N2 mantém duas casas decimais, P0 mostra uma proporção como porcentagem, e 0.00 ou 000 completam com zeros:
<echo value="1234567->format()" /> <!-- '1,234,567' because the commas split it into thousands -->
<echo value="1234.567->format('N2')" /> <!-- '1,234.57' because N2 keeps two decimal places, rounded -->
<echo value="0.075->format('P1')" /> <!-- '7.5 %' because P shows a share of 1 as a percentage -->
<echo value="7->format('000')" /> <!-- '007' because each 0 is a digit that must be shown -->
echo 1234567->format() // '1,234,567' because the commas split it into thousands
echo 1234.567->format('N2') // '1,234.57' because N2 keeps two decimal places, rounded
echo 0.075->format('P1') // '7.5 %' because P shows a share of 1 as a percentage
echo 7->format('000') // '007' because each 0 is a digit that must be shown
->is_even() é verdadeiro para um inteiro que 2 divide exatamente. Um número com decimais não é nem par nem ímpar:
<echo value="10->is_even()" /> <!-- true -->
<echo value="7->is_even()" /> <!-- false because 7 leaves 1 over when shared into twos -->
<echo value="-4->is_even()" /> <!-- true because negative numbers can be even too -->
<echo value="2.5->is_even()" /> <!-- false because it isn't a whole number -->
echo 10->is_even() // true
echo 7->is_even() // false because 7 leaves 1 over when shared into twos
echo -4->is_even() // true because negative numbers can be even too
echo 2.5->is_even() // false because it isn't a whole number
->is_odd() é verdadeiro para um inteiro que deixa resto 1 ao ser dividido por 2. Serve para alternar cores em linhas pares e ímpares:
<let name="rows" value="['tea', 'milk', 'juice']" />
<echo value="$rows->map(fn(drink, index) => $index->is_odd() ? 'grey' : 'white')" /> <!-- ['white', 'grey', 'white'] because rows 0 and 2 are even -->
<echo value="2.5->is_odd()" /> <!-- false because it isn't a whole number -->
$rows = ['tea', 'milk', 'juice']
echo $rows->map(fn(drink, index) => $index->is_odd() ? 'grey' : 'white') // ['white', 'grey', 'white'] because rows 0 and 2 are even
echo 2.5->is_odd() // false because it isn't a whole number
->max(other) retorna o maior entre o número e other. Serve para definir um piso: a resposta nunca fica abaixo de other:
<let name="balance" value="-12" />
<echo value="$balance->max(0)" /> <!-- 0 because 0 is larger than -12, so the shown balance never goes below 0 -->
<echo value="30->max(0)" /> <!-- 30 -->
$balance = -12
echo $balance->max(0) // 0 because 0 is larger than -12, so the shown balance never goes below 0
echo 30->max(0) // 30
->min(other) retorna o menor entre o número e other. Serve para definir um teto: a resposta nunca fica acima de other:
<let name="wanted" value="12" />
<let name="in_stock" value="10" />
<echo value="$wanted->min($in_stock)" /> <!-- 10 because you can't sell more than the 10 there are -->
$wanted = 12
$in_stock = 10
echo $wanted->min($in_stock) // 10 because you can't sell more than the 10 there are
Arredondado para um número de casas decimais (0 por padrão).
->round(digits?) arredonda para o inteiro mais próximo, ou para digits casas decimais. Um número exatamente no meio arredonda para longe de zero, como faria no papel:
<echo value="3.14159->round(digits: 2)" /> <!-- 3.14 because the next digit, 1, rounds down -->
<echo value="2.5->round()" /> <!-- 3 because halfway rounds away from zero -->
<echo value="-2.5->round()" /> <!-- -3 because halfway rounds away from zero on the negative side too -->
<echo value="9.996->round(digits: 2)" /> <!-- 10 because 9.996 is nearer 10.00 than 9.99 -->
echo 3.14159->round(digits: 2) // 3.14 because the next digit, 1, rounds down
echo 2.5->round() // 3 because halfway rounds away from zero
echo -2.5->round() // -3 because halfway rounds away from zero on the negative side too
echo 9.996->round(digits: 2) // 10 because 9.996 is nearer 10.00 than 9.99
Chama fn(i) para i de 0 até o número, e retorna os resultados.
->times(fn(i)) chama a função uma vez para cada inteiro de 0 até um abaixo do número, e devolve uma lista com o que ela retornou. Serve para montar uma lista de tamanho fixo:
<echo value="3->times(fn(i) => $i * $i)" /> <!-- [0, 1, 4] because i is 0, then 1, then 2 -->
<echo value="4->times(fn(i) => "Seat { $i + 1 }")->last()" /> <!-- 'Seat 4' because i stops at 3 -->
<echo value="0->times(fn(i) => $i)" /> <!-- [] because there is nothing to count -->
echo 3->times(fn(i) => $i * $i) // [0, 1, 4] because i is 0, then 1, then 2
echo 4->times(fn(i) => "Seat { $i + 1 }")->last() // 'Seat 4' because i stops at 3
echo 0->times(fn(i) => $i) // [] because there is nothing to count
Lê o número como um timestamp Unix, segundos desde 1970-01-01 UTC: 1795996800->to_date() é 30 de novembro de 2026. ->timestamp() transforma uma data de volta em um número.
->to_date() lê o número como um timestamp Unix, a quantidade de segundos desde o início de 1º de janeiro de 1970 em UTC, que é como muitos sistemas e APIs enviam datas. $date->timestamp() transforma uma data de volta nesse número. Só inteiros podem virar datas desse jeito; para avançar uma data, some uma duração, como 3d:
->to_int() descarta tudo depois do ponto decimal, mantendo só a parte inteira. Diferente de ->floor(), para um número negativo ele vai em direção a zero:
<echo value="9.99->to_int()" /> <!-- 9 because the .99 is dropped, not rounded -->
<echo value="-3.7->to_int()" /> <!-- -3 because the decimals are dropped, which moves towards zero -->
<echo value="-3.7->floor()" /> <!-- -4 because ->floor() always goes down -->
echo 9.99->to_int() // 9 because the .99 is dropped, not rounded
echo -3.7->to_int() // -3 because the decimals are dropped, which moves towards zero
echo -3.7->floor() // -4 because ->floor() always goes down
->to_number(default?) retorna o próprio número. Existe para que um valor que pode ser um número ou um texto possa chamar ->to_number() de qualquer forma. Em um texto, lê o número escrito ali:
<echo value="42->to_number()" /> <!-- 42 -->
<echo value="'12.5'->to_number() + 1" /> <!-- 13.5 because the text is read as a number first -->
<echo value="'none'->to_number(0)" /> <!-- 0 because 'none' isn't a number, so the default is used -->
echo 42->to_number() // 42
echo '12.5'->to_number() + 1 // 13.5 because the text is read as a number first
echo 'none'->to_number(0) // 0 because 'none' isn't a number, so the default is used
Exemplo
<echo>{ '42'->to_number() + 1 }</echo>
echo '42'->to_number() + 1
De KScript.Math
Estes precisam de <import package="KScript.Math" />import KScript.Math. Veja KScript.Math.