From c3bdacbf041c89b844f67efd29d7424efecd63bc Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 14 Jul 2020 19:16:13 +0530 Subject: [PATCH] doc: add info about _ separator in literals (#5823) --- doc/docs.md | 15 +++++++++++++++ vlib/builtin/int_test.v | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 5c2d8886db..70994982f9 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -388,18 +388,22 @@ println(s) // "hello\nworld" ```v a := 123 ``` + This will assign the value of 123 to `a`. By default `a` will have the type `int`. You can also use hexadecimal notation for integer literals: + ```v a := 0x7B ``` ... or binary notation for integer literals: + ```v a := 0b01111011 ``` ... or octal notation for specifying integer literals: + ```v a := 0o173 ``` @@ -407,8 +411,18 @@ a := 0o173 All of these will assign the same value 123 to `a`. `a` will have the type `int` no matter what notation you have used for the integer literal. +V also supports writing numbers with `_` as separator: + +```v +num := 1_000_000 // same as 1000000 +three := 0b0_11 // same as 0b11 +float_num := 3_122.55 // same as 3122.55 +hexa := 0xF_F // same as 255 +oct := 0o17_3 // same as 0o173 +``` If you want a different type of integer, you can use casting: + ```v a := i64(123) b := byte(42) @@ -416,6 +430,7 @@ c := i16(12345) ``` Assigning floating point numbers works the same way: + ```v f := 1.0 f1 := f64(3.14) diff --git a/vlib/builtin/int_test.v b/vlib/builtin/int_test.v index 94cc942d7d..257dd5d73b 100644 --- a/vlib/builtin/int_test.v +++ b/vlib/builtin/int_test.v @@ -144,6 +144,33 @@ fn test_oct() { assert x9 == 0 } +fn test_num_separator() { + // int + assert 100_000_0 == 1000000 + assert -2_23_4_6 == -22346 + assert 230_ == 230 + + // bin + assert 0b0_11 == 3 + assert -0b0_100 == -4 + assert 0b010_ == 2 + + // oct + assert 0o_173 == 123 + assert -0o_175 == -125 + assert -0o175_ == -125 + + // hex + assert 0x_FF == 255 + assert 0xFF_ == 255 + assert 0xF_F == 255 + + // f32 or f64 + assert 312_2.55 == 3122.55 + assert 312_2.55 == 3122.55 + +} + fn test_int_decl() { x1 := 0 x2 := 1333