Rounding floats

[XML] [Smart Pascal] [JavaScript] [Python] [output]

We provide several examples of the use of floating point numbers (floats). These can be difficult to read when the results of processing are presented with many decimal places. This example demonstrates the use of a function with two parameters and maths power, multiplication, division and round (to the nearest whole number).

We used the Blockly Playground to generate JavaScript and Python code from the same blocks.

The blocks

The blocks

XML Code of Blocks

<xml xmlns="http://www.w3.org/1999/xhtml">
  <block id="+8*MY2Qgyfr#ChKj%S[#" type="procedures_defreturn" x="-63" y="-12">
    <mutation>
      <arg name="floatNum"></arg>
      <arg name="intRange"></arg>
    </mutation>
    <field name="NAME">RoundTo</field>
    <comment pinned="false" h="80" w="160">Rounds a number to intRange decimal places</comment>
    <statement name="STACK">
      <block id="2![(zYAa3eU8A%RBFEjO" type="variables_set">
        <field name="VAR">floatPowerOfTen</field>
        <value name="VALUE">
          <block id="sa.ll@U8][(*UAbd`dLf" type="math_single">
            <field name="OP">POW10</field>
            <value name="NUM">
              <shadow id="57O)3jf+WAca=tRyeQ-8" type="math_number">
                <field name="NUM">9</field>
              </shadow>
              <block id="(mN=O)n-.:89~)9T_YpD" type="variables_get">
                <field name="VAR">intRange</field>
              </block>
            </value>
          </block>
        </value>
        <next>
          <block id="FV_B%twk5HoO90UPD}sC" type="variables_set">
            <field name="VAR">floatRoundedNum</field>
            <value name="VALUE">
              <block id="gT^cKMj-agh:c/t~^Mhf" type="math_arithmetic">
                <field name="OP">DIVIDE</field>
                <value name="A">
                  <shadow id="#)#g/Y[2`-}`=U$n,M6-" type="math_number">
                    <field name="NUM">1</field>
                  </shadow>
                  <block id="iHu|9a(oY^+5a|^5w5ZT" type="math_round">
                    <field name="OP">ROUND</field>
                    <value name="NUM">
                      <shadow id="b^HNQ5b8vFF:eQq/gy-w" type="math_number">
                        <field name="NUM">3.1</field>
                      </shadow>
                      <block id=",*K_Jyw]]Ed#6t/CkL?%" type="math_arithmetic">
                        <field name="OP">MULTIPLY</field>
                        <value name="A">
                          <shadow id="gA.%l5/]PX}K82s%X`oL" type="math_number">
                            <field name="NUM">1</field>
                          </shadow>
                          <block id="2%gfi[z?WZg$a0k;52,]" type="variables_get">
                            <field name="VAR">floatNum</field>
                          </block>
                        </value>
                        <value name="B">
                          <shadow id="f+XZm9`qBJqC9d@(iX}:" type="math_number">
                            <field name="NUM">1</field>
                          </shadow>
                          <block id="PI2$ToO}jebczg/MWneL" type="variables_get">
                            <field name="VAR">floatPowerOfTen</field>
                          </block>
                        </value>
                      </block>
                    </value>
                  </block>
                </value>
                <value name="B">
                  <shadow id="Qi3LO@eN-#K5G~3,y{d4" type="math_number">
                    <field name="NUM">1</field>
                  </shadow>
                  <block id="qPBVu8YaeVx#r+XqSQ%g" type="variables_get">
                    <field name="VAR">floatPowerOfTen</field>
                  </block>
                </value>
              </block>
            </value>
          </block>
        </next>
      </block>
    </statement>
    <value name="RETURN">
      <block id="W3p@gNtBbOLRNcQQhOCK" type="variables_get">
        <field name="VAR">floatRoundedNum</field>
      </block>
    </value>
  </block>
  <block id="SFkb]4n+N+m/!;IOi+5?" type="text_print" x="-63" y="138">
    <value name="TEXT">
      <shadow id="i}lUVATod@s@H?D4KUT|" type="text">
        <field name="TEXT">abc</field>
      </shadow>
      <block id="jl{J,3:vYJGAUR%a586N" type="text_join">
        <mutation items="1"></mutation>
        <value name="ADD0">
          <block id="E;|M`,[83`+kzA6(YZ=N" type="procedures_callreturn">
            <mutation name="RoundTo">
              <arg name="floatNum"></arg>
              <arg name="intRange"></arg>
            </mutation>
            <value name="ARG0">
              <block id="eZYCtn5KfPG@vsPS7QGe" type="math_number">
                <field name="NUM">123.456789</field>
              </block>
            </value>
            <value name="ARG1">
              <block id="C~|pFJG*a,euWOdNy-.s" type="math_number">
                <field name="NUM">3</field>
              </block>
            </value>
          </block>
        </value>
      </block>
    </value>
    <next>
      <block id="H4~aW]mJ%fQJyLZ=lk7Q" type="text_print">
        <value name="TEXT">
          <shadow id="i}lUVATod@s@H?D4KUT|" type="text">
            <field name="TEXT">abc</field>
          </shadow>
          <block id="H}V6_F*4NVizK`#I=-5Z" type="text_join">
            <mutation items="1"></mutation>
            <value name="ADD0">
              <block id="+Dwo#`;hh$W3m37BY/L_" type="procedures_callreturn">
                <mutation name="RoundTo">
                  <arg name="floatNum"></arg>
                  <arg name="intRange"></arg>
                </mutation>
                <value name="ARG0">
                  <block id="-@x)3MUp3QdAKqgmzmHK" type="math_number">
                    <field name="NUM">0.5</field>
                  </block>
                </value>
                <value name="ARG1">
                  <block id="_-p=.o}PR(-B!p6Ye=Yc" type="math_number">
                    <field name="NUM">1</field>
                  </block>
                </value>
              </block>
            </value>
          </block>
        </value>
        <next>
          <block id="jZDPZ%KEn2g61{e;#2QX" type="text_print">
            <value name="TEXT">
              <shadow id="i}lUVATod@s@H?D4KUT|" type="text">
                <field name="TEXT">abc</field>
              </shadow>
              <block id="03+G_JQHQZe0nUl)ns03" type="text_join">
                <mutation items="1"></mutation>
                <value name="ADD0">
                  <block id=":/ijq/K.L-]J*+o`t,b$" type="procedures_callreturn">
                    <mutation name="RoundTo">
                      <arg name="floatNum"></arg>
                      <arg name="intRange"></arg>
                    </mutation>
                    <value name="ARG0">
                      <block id="^qM:`l5SDdWciqs{cWkQ" type="math_number">
                        <field name="NUM">3.14159</field>
                      </block>
                    </value>
                    <value name="ARG1">
                      <block id="G%M7%Mp~QL@Iqx9#McU/" type="math_number">
                        <field name="NUM">3</field>
                      </block>
                    </value>
                  </block>
                </value>
              </block>
            </value>
          </block>
        </next>
      </block>
    </next>
  </block>
</xml>

Generated Smart Pascal Code

var floatRoundedNum: Float;
var floatPowerOfTen: Float;
var floatNum: Float;
var intRange: Integer;

{
  Rounds a number  to intRange decimal places
}
function RoundTo(floatNum: Float; intRange: Integer): Float;
begin
  floatPowerOfTen := Power(10,intRange);
  floatRoundedNum := Round(floatNum * floatPowerOfTen) / floatPowerOfTen;
  Result := floatRoundedNum;
end;


function Str(v: Variant) : string;
begin
  asm
    if (@v === 0) {
      @Result = '0';
    }
    else if (@v === '') {
      @Result = '';
    }
    else if (isNaN(@v)) {
      @Result = @v;
    }
    else {
      @Result = (@v).toString();
    }
  end;
end;



Console.writeln(Str(RoundTo(123.456789, 3)));
Console.writeln(Str(RoundTo(0.5, 1)));
Console.writeln(Str(RoundTo(3.14159, 3)));
    

Generated JavaScript

var floatRoundedNum, floatPowerOfTen, floatNum, intRange;

/**
 * Rounds a number to intRange decimal places
 */
function RoundTo(floatNum, intRange) {
  floatPowerOfTen = Math.pow(10,intRange);
  floatRoundedNum = Math.round(floatNum * floatPowerOfTen) / floatPowerOfTen;
  return floatRoundedNum;
}


window.alert(String(RoundTo(123.456789, 3)));
window.alert(String(RoundTo(0.5, 1)));
window.alert(String(RoundTo(3.14159, 3)));

Generated Python Code

import math

floatRoundedNum = None
floatPowerOfTen = None
floatNum = None
intRange = None

"""Rounds a number to intRange decimal places
"""
def RoundTo(floatNum, intRange):
  global floatRoundedNum, floatPowerOfTen
  floatPowerOfTen = math.pow(10,intRange)
  floatRoundedNum = round(floatNum * floatPowerOfTen) / floatPowerOfTen
  return floatRoundedNum


print(str(RoundTo(123.456789, 3)))
print(str(RoundTo(0.5, 1)))
print(str(RoundTo(3.14159, 3)))

Copy of Output

123.457
0.5
3.142
Programming - a skill for life!

XML, images and generated Smart Pascal code of examples including loops, arrays, validation and recursion